home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / nt / emacssrc.zip / EMACSSRC.TAR / emacs-19.17 / src / xterm.c < prev    next >
C/C++ Source or Header  |  1993-10-13  |  136KB  |  4,841 lines

  1. /* X Communication module for terminals which understand the X protocol.
  2.    Copyright (C) 1989, 1993 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU Emacs.
  5.  
  6. GNU Emacs is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10.  
  11. GNU Emacs is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Emacs; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* Serious problems:
  21.  
  22.    Kludge: dup2 is used to put the X-connection socket into desc # 0
  23.    so that wait_reading_process_input will wait for it in place of
  24.    actual terminal input.
  25.    
  26. */
  27.  
  28. #define NEW_SELECTIONS
  29.  
  30. /* On 4.3 these lose if they come after xterm.h.  */
  31. /* On HP-UX 8.0 signal.h loses if it comes after config.h.  */
  32. /* Putting these at the beginning seems to be standard for other .c files.  */
  33. #include <stdio.h>
  34. #include <signal.h>
  35.  
  36. #include "config.h"
  37.  
  38. #ifdef HAVE_X_WINDOWS
  39.  
  40. #include "lisp.h"
  41. #include "blockinput.h"
  42.  
  43. /* This may include sys/types.h, and that somehow loses
  44.    if this is not done before the other system files.  */
  45. #include "xterm.h"
  46. #include <X11/cursorfont.h>
  47.  
  48. #ifndef USG
  49. /* Load sys/types.h if not already loaded.
  50.    In some systems loading it twice is suicidal.  */
  51. #ifndef makedev
  52. #include <sys/types.h>
  53. #endif /* makedev */
  54. #endif /* USG */
  55.  
  56. #ifdef BSD
  57. #include <sys/ioctl.h>
  58. #include <strings.h>
  59. #else /* ! defined (BSD) */
  60. #ifndef VMS
  61. #include <string.h>
  62. #endif
  63. #endif /* ! defined (BSD) */
  64.  
  65. #include "systty.h"
  66. #include "systime.h"
  67.  
  68. #include <fcntl.h>
  69. #include <ctype.h>
  70. #include <errno.h>
  71. #include <setjmp.h>
  72. #include <sys/stat.h>
  73. #include <sys/param.h>
  74.  
  75. #include "dispextern.h"
  76. #include "termhooks.h"
  77. #include "termopts.h"
  78. #include "termchar.h"
  79. #if 0
  80. #include "sink.h"
  81. #include "sinkmask.h"
  82. #endif /* ! 0 */
  83. #include "gnu.h"
  84. #include "frame.h"
  85. #include "disptab.h"
  86. #include "buffer.h"
  87. #include "window.h"
  88.  
  89. #ifdef HAVE_X11
  90. #define XMapWindow XMapRaised        /* Raise them when mapping. */
  91. #else /* ! defined (HAVE_X11) */
  92. #include <X/Xkeyboard.h>
  93. /*#include <X/Xproto.h>    */
  94. #endif /* ! defined (HAVE_X11) */
  95.  
  96. #include "sysfdset.h"
  97.  
  98. /* For sending Meta-characters.  Do we need this? */
  99. #define METABIT 0200
  100.  
  101. #define min(a,b) ((a)<(b) ? (a) : (b))
  102. #define max(a,b) ((a)>(b) ? (a) : (b))
  103.  
  104. /* Nonzero means we must reprint all windows
  105.    because 1) we received an ExposeWindow event
  106.    or 2) we received too many ExposeRegion events to record.
  107.  
  108.    This is never needed under X11.  */
  109. static int expose_all_windows;
  110.  
  111. /* Nonzero means we must reprint all icon windows.  */
  112.  
  113. static int expose_all_icons;
  114.  
  115. #ifndef HAVE_X11
  116. /* ExposeRegion events, when received, are copied into this queue
  117.    for later processing.  */
  118.  
  119. static struct event_queue x_expose_queue;
  120.  
  121. /* ButtonPressed and ButtonReleased events, when received,
  122.    are copied into this queue for later processing.  */
  123.  
  124. struct event_queue x_mouse_queue;
  125. #endif /* HAVE_X11 */
  126.  
  127. #if defined (SIGIO) && defined (FIONREAD)
  128. int BLOCK_INPUT_mask;
  129. #endif /* ! defined (SIGIO) && defined (FIONREAD) */
  130.  
  131. /* The id of a bitmap used for icon windows.
  132.    One such map is shared by all Emacs icon windows.
  133.    This is zero if we have not yet had a need to create the bitmap.  */
  134.  
  135. static Bitmap icon_bitmap;
  136.  
  137. /* Font used for text icons.  */
  138.  
  139. static FONT_TYPE *icon_font_info;
  140.  
  141. /* Stuff for dealing with the main icon title. */
  142.  
  143. extern Lisp_Object Vcommand_line_args;
  144. char *hostname, *x_id_name;
  145.  
  146. /* This is the X connection that we are using.  */
  147.  
  148. Display *x_current_display;
  149.  
  150. /* The cursor to use for vertical scroll bars on x_current_display.  */
  151. static Cursor x_vertical_scroll_bar_cursor;
  152.  
  153. /* Frame being updated by update_frame.  This is declared in term.c.
  154.    This is set by update_begin and looked at by all the
  155.    XT functions.  It is zero while not inside an update.
  156.    In that case, the XT functions assume that `selected_frame'
  157.    is the frame to apply to.  */
  158. extern struct frame *updating_frame;
  159.  
  160. /* The frame (if any) which has the X window that has keyboard focus.
  161.    Zero if none.  This is examined by Ffocus_frame in frame.c.  Note
  162.    that a mere EnterNotify event can set this; if you need to know the
  163.    last frame specified in a FocusIn or FocusOut event, use
  164.    x_focus_event_frame.  */
  165. struct frame *x_focus_frame;
  166.  
  167. /* The last frame mentioned in a FocusIn or FocusOut event.  This is
  168.    separate from x_focus_frame, because whether or not LeaveNotify
  169.    events cause us to lose focus depends on whether or not we have
  170.    received a FocusIn event for it.  */
  171. struct frame *x_focus_event_frame;
  172.  
  173. /* The frame which currently has the visual highlight, and should get
  174.    keyboard input (other sorts of input have the frame encoded in the
  175.    event).  It points to the X focus frame's selected window's
  176.    frame.  It differs from x_focus_frame when we're using a global
  177.    minibuffer.  */
  178. static struct frame *x_highlight_frame;
  179.  
  180. /* From .Xdefaults, the value of "emacs.WarpMouse".  If non-zero,
  181.    mouse is moved to inside of frame when frame is de-iconified.  */
  182.  
  183. static int warp_mouse_on_deiconify;
  184.  
  185. /* During an update, maximum vpos for ins/del line operations to affect.  */
  186.  
  187. static int flexlines;
  188.  
  189. /* During an update, nonzero if chars output now should be highlighted.  */
  190.  
  191. static int highlight;
  192.  
  193. /* Nominal cursor position -- where to draw output.
  194.    During an update, these are different from the cursor-box position.  */
  195.  
  196. static int curs_x;
  197. static int curs_y;
  198.  
  199. #ifdef HAVE_X11
  200. /* `t' if a mouse button is depressed. */
  201.  
  202. extern Lisp_Object Vmouse_depressed;
  203.  
  204. /* Tells if a window manager is present or not. */
  205.  
  206. extern Lisp_Object Vx_no_window_manager;
  207.  
  208. /* Timestamp that we requested selection data was made. */
  209. extern Time requestor_time;
  210.  
  211. /* ID of the window requesting selection data. */
  212. extern Window requestor_window;
  213.  
  214. /* Nonzero enables some debugging for the X interface code. */
  215. extern int _Xdebug;
  216.  
  217. #else /* ! defined (HAVE_X11) */
  218.  
  219. /* Bit patterns for the mouse cursor.  */
  220.  
  221. short MouseCursor[] = {
  222.   0x0000, 0x0008, 0x0018, 0x0038,
  223.   0x0078, 0x00f8, 0x01f8, 0x03f8,
  224.   0x07f8, 0x00f8, 0x00d8, 0x0188,
  225.   0x0180, 0x0300, 0x0300, 0x0000};
  226.  
  227. short MouseMask[] = {
  228.   0x000c, 0x001c, 0x003c, 0x007c,
  229.   0x00fc, 0x01fc, 0x03fc, 0x07fc,
  230.   0x0ffc, 0x0ffc, 0x01fc, 0x03dc,
  231.   0x03cc, 0x0780, 0x0780, 0x0300};
  232.  
  233. static short grey_bits[] = {
  234.   0x0005, 0x000a, 0x0005, 0x000a};
  235.  
  236. static Pixmap GreyPixmap = 0;
  237. #endif /* ! defined (HAVE_X11) */
  238.  
  239. /* From time to time we get info on an Emacs window, here.  */
  240.  
  241. static WINDOWINFO_TYPE windowinfo;
  242.  
  243. extern int errno;
  244.  
  245. /* A mask of extra modifier bits to put into every keyboard char.  */
  246. extern int extra_keyboard_modifiers;
  247.  
  248. extern Display *XOpenDisplay ();
  249. extern Window XCreateWindow ();
  250.  
  251. extern Cursor XCreateCursor ();
  252. extern FONT_TYPE *XOpenFont ();
  253.  
  254. static void flashback ();
  255.  
  256. #ifndef HAVE_X11
  257. static void dumpqueue ();
  258. #endif /* HAVE_X11 */
  259.  
  260. void dumpborder ();
  261. static int XTcursor_to ();
  262. static int XTclear_end_of_line ();
  263.  
  264.  
  265. /* Starting and ending updates. 
  266.  
  267.    These hooks are called by update_frame at the beginning and end
  268.    of a frame update.  We record in `updating_frame' the identity
  269.    of the frame being updated, so that the XT... functions do not
  270.    need to take a frame as argument.  Most of the XT... functions
  271.    should never be called except during an update, the only exceptions
  272.    being XTcursor_to, XTwrite_char and XTreassert_line_highlight.  */
  273.  
  274. extern int mouse_track_top, mouse_track_left, mouse_track_width;
  275.  
  276. static
  277. XTupdate_begin (f)
  278.      struct frame *f;
  279. {    
  280.   int mask;
  281.  
  282.   if (f == 0)
  283.     abort ();
  284.  
  285.   flexlines = f->height;
  286.   highlight = 0;
  287.  
  288.   BLOCK_INPUT;
  289. #ifndef HAVE_X11
  290.   dumpqueue ();
  291. #endif /* HAVE_X11 */
  292.   UNBLOCK_INPUT;
  293. }
  294.  
  295. #ifndef HAVE_X11
  296. static void x_do_pending_expose ();
  297. #endif
  298.  
  299. static
  300. XTupdate_end (f)
  301.      struct frame *f;
  302. {    
  303.   int mask;
  304.  
  305.   if (updating_frame == 0
  306.       || updating_frame != f)
  307.     abort ();
  308.  
  309.   BLOCK_INPUT;
  310. #ifndef HAVE_X11
  311.   dumpqueue ();
  312.   x_do_pending_expose ();
  313. #endif /* HAVE_X11 */
  314.  
  315.   x_display_cursor (f, 1);
  316.  
  317.   XFlushQueue ();
  318.   UNBLOCK_INPUT;
  319. }
  320.  
  321. /* External interface to control of standout mode.
  322.    Call this when about to modify line at position VPOS
  323.    and not change whether it is highlighted.  */
  324.  
  325. XTreassert_line_highlight (new, vpos)
  326.      int new, vpos;
  327. {
  328.   highlight = new;
  329. }
  330.  
  331. /* Call this when about to modify line at position VPOS
  332.    and change whether it is highlighted.  */
  333.  
  334. static
  335. XTchange_line_highlight (new_highlight, vpos, first_unused_hpos)
  336.      int new_highlight, vpos, first_unused_hpos;
  337. {
  338.   highlight = new_highlight;
  339.   XTcursor_to (vpos, 0);
  340.   XTclear_end_of_line (updating_frame->width);
  341. }
  342.  
  343. /* This is used when starting Emacs and when restarting after suspend.
  344.    When starting Emacs, no X window is mapped.  And nothing must be done
  345.    to Emacs's own window if it is suspended (though that rarely happens).  */
  346.  
  347. static
  348. XTset_terminal_modes ()
  349. {
  350. }
  351.  
  352. /* This is called when exiting or suspending Emacs.
  353.    Exiting will make the X-windows go away, and suspending
  354.    requires no action.  */
  355.  
  356. static
  357. XTreset_terminal_modes ()
  358. {
  359. /*  XTclear_frame ();  */
  360. }
  361.  
  362. /* Set the nominal cursor position of the frame.
  363.    This is where display update commands will take effect.
  364.    This does not affect the place where the cursor-box is displayed.  */
  365.  
  366. static int
  367. XTcursor_to (row, col)
  368.      register int row, col;
  369. {
  370.   int mask;
  371.   int orow = row;
  372.  
  373.   curs_x = col;
  374.   curs_y = row;
  375.  
  376.   if (updating_frame == 0)
  377.     {
  378.       BLOCK_INPUT;
  379.       x_display_cursor (selected_frame, 1);
  380.       XFlushQueue ();
  381.       UNBLOCK_INPUT;
  382.     }
  383. }
  384.  
  385. /* Display a sequence of N glyphs found at GP.
  386.    WINDOW is the x-window to output to.  LEFT and TOP are starting coords.
  387.    HL is 1 if this text is highlighted, 2 if the cursor is on it.
  388.  
  389.    FONT is the default font to use (for glyphs whose font-code is 0).
  390.  
  391.    Since the display generation code is responsible for calling
  392.    compute_char_face and compute_glyph_face on everything it puts in
  393.    the display structure, we can assume that the face code on each
  394.    glyph is a valid index into FRAME_COMPUTED_FACES (f), and the one
  395.    to which we can actually apply intern_face.  */
  396.  
  397. #if 1
  398. /* This is the multi-face code.  */
  399.  
  400. static void
  401. dumpglyphs (f, left, top, gp, n, hl)
  402.      struct frame *f;
  403.      int left, top;
  404.      register GLYPH *gp; /* Points to first GLYPH. */
  405.      register int n;  /* Number of glyphs to display. */
  406.      int hl;
  407. {
  408.   /* Holds characters to be displayed. */
  409.   char *buf = (char *) alloca (f->width * sizeof (*buf));
  410.   register char *cp;        /* Steps through buf[]. */
  411.   register int tlen = GLYPH_TABLE_LENGTH;
  412.   register Lisp_Object *tbase = GLYPH_TABLE_BASE;
  413.   Window window = FRAME_X_WINDOW (f);
  414.  
  415.   while (n > 0)
  416.     {
  417.       /* Get the face-code of the next GLYPH.  */
  418.       int cf, len;
  419.       int g = *gp;
  420.  
  421.       GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
  422.       cf = GLYPH_FACE (g);
  423.  
  424.       /* Find the run of consecutive glyphs with the same face-code.
  425.      Extract their character codes into BUF.  */
  426.       cp = buf;
  427.       while (n > 0)
  428.     {
  429.       g = *gp;
  430.       GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
  431.       if (GLYPH_FACE (g) != cf)
  432.         break;
  433.  
  434.       *cp++ = GLYPH_CHAR (g);
  435.       --n;
  436.       ++gp;
  437.     }
  438.  
  439.       /* LEN gets the length of the run.  */
  440.       len = cp - buf;
  441.  
  442.       /* Now output this run of chars, with the font and pixel values
  443.      determined by the face code CF.  */
  444.       {
  445.     struct face *face = FRAME_DEFAULT_FACE (f);
  446.     FONT_TYPE *font = FACE_FONT (face);
  447.     GC gc = FACE_GC (face);
  448.     int defaulted = 1;
  449.     int gc_temporary = 0;
  450.  
  451.     /* First look at the face of the text itself.  */
  452.     if (cf != 0)
  453.       {
  454.         /* The face codes on the glyphs must be valid indices into the
  455.            frame's face table.  */
  456.         if (cf < 0 || cf >= FRAME_N_COMPUTED_FACES (f)
  457.         || FRAME_COMPUTED_FACES (f) [cf] == 0)
  458.           abort ();
  459.  
  460.         if (cf == 1)
  461.           face = FRAME_MODE_LINE_FACE (f);
  462.         else
  463.           face = intern_face (f, FRAME_COMPUTED_FACES (f) [cf]);
  464.         font = FACE_FONT (face);
  465.         gc = FACE_GC (face);
  466.         defaulted = 0;
  467.       }
  468.  
  469.     /* Then comes the distinction between modeline and normal text.  */
  470.     else if (hl == 0)
  471.       ;
  472.     else if (hl == 1)
  473.       {
  474.         face = FRAME_MODE_LINE_FACE (f);
  475.         font = FACE_FONT (face);
  476.         gc   = FACE_GC   (face);
  477.         defaulted = 0;
  478.       }
  479.  
  480. #define FACE_DEFAULT (~0)
  481.  
  482.     /* Now override that if the cursor's on this character.  */
  483.     if (hl == 2)
  484.       {
  485.         if (defaulted
  486.         || !face->font
  487.         || (int) face->font == FACE_DEFAULT)
  488.           {
  489.         gc = f->display.x->cursor_gc;
  490.           }
  491.         /* Cursor on non-default face: must merge.  */
  492.         else
  493.           {
  494.         XGCValues xgcv;
  495.         unsigned long mask;
  496.  
  497.         xgcv.background = f->display.x->cursor_pixel;
  498.         xgcv.foreground = f->display.x->cursor_foreground_pixel;
  499.         xgcv.font = face->font->fid;
  500.         xgcv.graphics_exposures = 0;
  501.         mask = GCForeground | GCBackground | GCFont | GCGraphicsExposures;
  502.         gc = XCreateGC (x_current_display, FRAME_X_WINDOW (f),
  503.                 mask, &xgcv);
  504. #if 0
  505.         if (face->stipple && face->stipple != FACE_DEFAULT)
  506.           XSetStipple (x_current_display, gc, face->stipple);
  507. #endif
  508.         gc_temporary = 1;
  509.           }
  510.       }
  511.  
  512.     if ((int) font == FACE_DEFAULT)
  513.       font = f->display.x->font;
  514.  
  515.     XDrawImageString (x_current_display, window, gc,
  516.               left, top + FONT_BASE (font), buf, len);
  517.  
  518.     if (gc_temporary)
  519.       XFreeGC (x_current_display, gc);
  520.  
  521.     /* We should probably check for XA_UNDERLINE_POSITION and
  522.        XA_UNDERLINE_THICKNESS properties on the font, but let's
  523.        just get the thing working, and come back to that.  */
  524.     {
  525.       int underline_position = 1;
  526.  
  527.       if (font->descent <= underline_position)
  528.         underline_position = font->descent - 1;
  529.  
  530.       if (face->underline)
  531.         XFillRectangle (x_current_display, FRAME_X_WINDOW (f),
  532.                 FACE_GC (face),
  533.                 left, (top
  534.                    + FONT_BASE (font)
  535.                    + underline_position),
  536.                 len * FONT_WIDTH (font), 1);
  537.     }
  538.  
  539.     left += len * FONT_WIDTH (font);
  540.       }
  541.     }
  542. }
  543. #endif /* 1 */
  544.  
  545. #if 0
  546. /* This is the old single-face code.  */
  547.  
  548. static void
  549. dumpglyphs (f, left, top, gp, n, hl, font)
  550.      struct frame *f;
  551.      int left, top;
  552.      register GLYPH *gp; /* Points to first GLYPH. */
  553.      register int n;  /* Number of glyphs to display. */
  554.      int hl;
  555.      FONT_TYPE *font;
  556. {
  557.   register int len;
  558.   Window window = FRAME_X_WINDOW (f);
  559.   GC drawing_gc =   (hl == 2 ? f->display.x->cursor_gc
  560.                      : (hl ? f->display.x->reverse_gc
  561.                    : f->display.x->normal_gc));
  562.  
  563.   if (sizeof (GLYPH) == sizeof (XChar2b))
  564.     XDrawImageString16 (x_current_display, window, drawing_gc,
  565.             left, top + FONT_BASE (font), (XChar2b *) gp, n);
  566.   else if (sizeof (GLYPH) == sizeof (unsigned char))
  567.     XDrawImageString (x_current_display, window, drawing_gc,
  568.               left, top + FONT_BASE (font), (char *) gp, n);
  569.   else
  570.     /* What size of glyph ARE you using?  And does X have a function to
  571.        draw them?  */
  572.     abort ();
  573. }
  574. #endif
  575.  
  576. /* Output some text at the nominal frame cursor position.
  577.    Advance the cursor over the text.
  578.    Output LEN glyphs at START.
  579.  
  580.    `highlight', set up by XTreassert_line_highlight or XTchange_line_highlight,
  581.    controls the pixel values used for foreground and background.  */
  582.  
  583. static
  584. XTwrite_glyphs (start, len)
  585.      register GLYPH *start;
  586.      int len;
  587. {
  588.   register int temp_length;
  589.   int mask;
  590.   struct frame *f;
  591.  
  592.   BLOCK_INPUT;
  593.  
  594.   f = updating_frame;
  595.   if (f == 0)
  596.     {
  597.       f = selected_frame;
  598.       /* If not within an update,
  599.      output at the frame's visible cursor.  */
  600.       curs_x = f->cursor_x;
  601.       curs_y = f->cursor_y;
  602.     }
  603.  
  604.   dumpglyphs (f,
  605.           CHAR_TO_PIXEL_COL (f, curs_x),
  606.           CHAR_TO_PIXEL_ROW (f, curs_y),
  607.           start, len, highlight);
  608.  
  609.   /* If we drew on top of the cursor, note that it is turned off.  */
  610.   if (curs_y == f->phys_cursor_y
  611.       && curs_x <= f->phys_cursor_x
  612.       && curs_x + len > f->phys_cursor_x)
  613.     f->phys_cursor_x = -1;
  614.   
  615.   if (updating_frame == 0)
  616.     {
  617.       f->cursor_x += len;
  618.       x_display_cursor (f, 1);
  619.       f->cursor_x -= len;
  620.     }
  621.   else
  622.     curs_x += len;
  623.  
  624.   UNBLOCK_INPUT;
  625. }
  626.  
  627. /* Clear to the end of the line.
  628.    Erase the current text line from the nominal cursor position (inclusive)
  629.    to column FIRST_UNUSED (exclusive).  The idea is that everything
  630.    from FIRST_UNUSED onward is already erased.  */
  631.   
  632. static int
  633. XTclear_end_of_line (first_unused)
  634.      register int first_unused;
  635. {
  636.   struct frame *f = updating_frame;
  637.   int mask;
  638.  
  639.   if (f == 0)
  640.     abort ();
  641.  
  642.   if (curs_y < 0 || curs_y >= f->height)
  643.     return;
  644.   if (first_unused <= 0)
  645.     return;
  646.  
  647.   if (first_unused >= f->width)
  648.     first_unused = f->width;
  649.  
  650.   BLOCK_INPUT;
  651.  
  652.   /* Notice if the cursor will be cleared by this operation.  */
  653.   if (curs_y == f->phys_cursor_y
  654.       && curs_x <= f->phys_cursor_x
  655.       && f->phys_cursor_x < first_unused)
  656.     f->phys_cursor_x = -1;
  657.  
  658. #ifdef HAVE_X11
  659.   XClearArea (x_current_display, FRAME_X_WINDOW (f),
  660.           CHAR_TO_PIXEL_COL (f, curs_x),
  661.           CHAR_TO_PIXEL_ROW (f, curs_y),
  662.           FONT_WIDTH (f->display.x->font) * (first_unused - curs_x),
  663.           FONT_HEIGHT (f->display.x->font), False);
  664.           
  665. #else /* ! defined (HAVE_X11) */
  666.   XPixSet (FRAME_X_WINDOW (f),
  667.        CHAR_TO_PIXEL_COL (f, curs_x),
  668.        CHAR_TO_PIXEL_ROW (f, curs_y),
  669.        FONT_WIDTH (f->display.x->font) * (first_unused - curs_x),
  670.        FONT_HEIGHT (f->display.x->font),
  671.        f->display.x->background_pixel);    
  672. #endif /* ! defined (HAVE_X11) */
  673.  
  674.   UNBLOCK_INPUT;
  675. }
  676.  
  677. static
  678. XTclear_frame ()
  679. {
  680.   int mask;
  681.   struct frame *f = updating_frame;
  682.  
  683.   if (f == 0)
  684.     f = selected_frame;
  685.  
  686.   f->phys_cursor_x = -1;    /* Cursor not visible.  */
  687.   curs_x = 0;            /* Nominal cursor position is top left.  */
  688.   curs_y = 0;
  689.   
  690.   BLOCK_INPUT;
  691.  
  692.   XClear (FRAME_X_WINDOW (f));
  693.  
  694.   /* We have to clear the scroll bars, too.  If we have changed
  695.      colors or something like that, then they should be notified.  */
  696.   x_scroll_bar_clear (f);
  697.  
  698. #ifndef HAVE_X11
  699.   dumpborder (f, 0);
  700. #endif /* HAVE_X11 */
  701.  
  702.   XFlushQueue ();
  703.   UNBLOCK_INPUT;
  704. }
  705.  
  706. /* Invert the middle quarter of the frame for .15 sec.  */
  707.  
  708. /* We use the select system call to do the waiting, so we have to make sure
  709.    it's available.  If it isn't, we just won't do visual bells.  */
  710. #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
  711.  
  712. /* Subtract the `struct timeval' values X and Y,
  713.    storing the result in RESULT.
  714.    Return 1 if the difference is negative, otherwise 0.  */
  715.  
  716. static int
  717. timeval_subtract (result, x, y)
  718.      struct timeval *result, x, y;
  719. {
  720.   /* Perform the carry for the later subtraction by updating y.
  721.      This is safer because on some systems
  722.      the tv_sec member is unsigned.  */
  723.   if (x.tv_usec < y.tv_usec)
  724.     {
  725.       int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
  726.       y.tv_usec -= 1000000 * nsec;
  727.       y.tv_sec += nsec;
  728.     }
  729.   if (x.tv_usec - y.tv_usec > 1000000)
  730.     {
  731.       int nsec = (y.tv_usec - x.tv_usec) / 1000000;
  732.       y.tv_usec += 1000000 * nsec;
  733.       y.tv_sec -= nsec;
  734.     }
  735.  
  736.   /* Compute the time remaining to wait.  tv_usec is certainly positive.  */
  737.   result->tv_sec = x.tv_sec - y.tv_sec;
  738.   result->tv_usec = x.tv_usec - y.tv_usec;
  739.  
  740.   /* Return indication of whether the result should be considered negative.  */
  741.   return x.tv_sec < y.tv_sec;
  742. }
  743.  
  744. XTflash (f)
  745.      struct frame *f;
  746. {
  747.   BLOCK_INPUT;
  748.  
  749.   {
  750.     GC gc;
  751.  
  752.     /* Create a GC that will use the GXxor function to flip foreground pixels
  753.        into background pixels.  */
  754.     {
  755.       XGCValues values;
  756.  
  757.       values.function = GXxor;
  758.       values.foreground = (f->display.x->foreground_pixel
  759.                ^ f->display.x->background_pixel);
  760.       
  761.       gc = XCreateGC (x_current_display, FRAME_X_WINDOW (f),
  762.               GCFunction | GCForeground, &values);
  763.     }
  764.  
  765.     {
  766.       int width  = PIXEL_WIDTH  (f);
  767.       int height = PIXEL_HEIGHT (f);
  768.  
  769.       XFillRectangle (x_current_display, FRAME_X_WINDOW (f), gc,
  770.               width/4, height/4, width/2, height/2);
  771.       XFlush (x_current_display);
  772.  
  773.       {
  774.     struct timeval wakeup, now;
  775.  
  776.     gettimeofday (&wakeup, (struct timezone *) 0);
  777.  
  778.     /* Compute time to wait until, propagating carry from usecs.  */
  779.     wakeup.tv_usec += 150000;
  780.     wakeup.tv_sec += (wakeup.tv_usec / 1000000);
  781.     wakeup.tv_usec %= 1000000;
  782.  
  783.     /* Keep waiting until past the time wakeup.  */
  784.     while (1)
  785.       {
  786.         struct timeval timeout;
  787.  
  788.         gettimeofday (&timeout, (struct timezone *)0);
  789.  
  790.         /* In effect, timeout = wakeup - timeout.
  791.            Break if result would be negative.  */
  792.         if (timeval_subtract (&timeout, wakeup, timeout))
  793.           break;
  794.  
  795.         /* Try to wait that long--but we might wake up sooner.  */
  796.         select (0, 0, 0, 0, &timeout);
  797.       }
  798.       }
  799.     
  800.       XFillRectangle (x_current_display, FRAME_X_WINDOW (f), gc,
  801.               width/4, height/4, width/2, height/2);
  802.       XFreeGC (x_current_display, gc);
  803.       XFlush (x_current_display);
  804.     }
  805.   }
  806.  
  807.   UNBLOCK_INPUT;
  808. }
  809.  
  810. #endif
  811.  
  812.  
  813. /* Make audible bell.  */
  814.  
  815. #ifdef HAVE_X11
  816. #define XRINGBELL XBell(x_current_display, 0)
  817. #else /* ! defined (HAVE_X11) */
  818. #define XRINGBELL XFeep(0);
  819. #endif /* ! defined (HAVE_X11) */
  820.  
  821. XTring_bell ()
  822. {
  823.   if (x_current_display == 0)
  824.     return;
  825.  
  826. #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
  827.   if (visible_bell)
  828.     XTflash (selected_frame);
  829.   else
  830. #endif
  831.     {
  832.       BLOCK_INPUT;
  833.       XRINGBELL;
  834.       XFlushQueue ();
  835.       UNBLOCK_INPUT;
  836.     }
  837. }
  838.  
  839. /* Insert and delete character.
  840.    These are not supposed to be used because we are supposed to turn
  841.    off the feature of using them.  */
  842.  
  843. static 
  844. XTinsert_glyphs (start, len)
  845.      register char *start;
  846.      register int len;
  847. {
  848.   abort ();
  849. }
  850.  
  851. static 
  852. XTdelete_glyphs (n)
  853.      register int n;
  854. {
  855.   abort ();
  856. }
  857.  
  858. /* Specify how many text lines, from the top of the window,
  859.    should be affected by insert-lines and delete-lines operations.
  860.    This, and those operations, are used only within an update
  861.    that is bounded by calls to XTupdate_begin and XTupdate_end.  */
  862.  
  863. static
  864. XTset_terminal_window (n)
  865.      register int n;
  866. {
  867.   if (updating_frame == 0)
  868.     abort ();
  869.  
  870.   if ((n <= 0) || (n > updating_frame->height))
  871.     flexlines = updating_frame->height;
  872.   else
  873.     flexlines = n;
  874. }
  875.  
  876. /* Perform an insert-lines operation.
  877.    Insert N lines at a vertical position curs_y.  */
  878.  
  879. static void
  880. stufflines (n)
  881.      register int n;
  882. {
  883.   register int topregion, bottomregion;
  884.   register int length, newtop, mask;
  885.   register struct frame *f = updating_frame;
  886.   int intborder = f->display.x->internal_border_width;
  887.  
  888.   if (curs_y >= flexlines)
  889.     return;
  890.  
  891.   topregion = curs_y;
  892.   bottomregion = flexlines - (n + 1);
  893.   newtop = topregion + n;
  894.   length = (bottomregion - topregion) + 1;
  895.  
  896. #ifndef HAVE_X11
  897.   dumpqueue ();
  898. #endif /* HAVE_X11 */
  899.  
  900.   if ((length > 0) && (newtop <= flexlines))
  901.     {
  902. #ifdef HAVE_X11
  903.       XCopyArea (x_current_display, FRAME_X_WINDOW (f),
  904.          FRAME_X_WINDOW (f), f->display.x->normal_gc,
  905.          intborder, CHAR_TO_PIXEL_ROW (f, topregion),
  906.          f->width * FONT_WIDTH (f->display.x->font),
  907.          length * FONT_HEIGHT (f->display.x->font), intborder,
  908.          CHAR_TO_PIXEL_ROW (f, newtop));
  909. #else /* ! defined (HAVE_X11) */
  910.       XMoveArea (FRAME_X_WINDOW (f),
  911.          intborder, CHAR_TO_PIXEL_ROW (f, topregion),
  912.          intborder, CHAR_TO_PIXEL_ROW (f, newtop),
  913.          f->width * FONT_WIDTH (f->display.x->font),
  914.          length * FONT_HEIGHT (f->display.x->font));
  915.       /* Now we must process any ExposeRegion events that occur
  916.      if the area being copied from is obscured.
  917.      We can't let it wait because further i/d operations
  918.      may want to copy this area to another area.  */
  919.       x_read_exposes ();
  920. #endif /* ! defined (HAVE_X11) */
  921.     }
  922.  
  923.   newtop = min (newtop, (flexlines - 1));
  924.   length = newtop - topregion;
  925.   if (length > 0)
  926.     {
  927. #ifdef HAVE_X11
  928.       XClearArea (x_current_display, FRAME_X_WINDOW (f), intborder, 
  929.           CHAR_TO_PIXEL_ROW (f, topregion),
  930.           f->width * FONT_WIDTH (f->display.x->font),
  931.           n * FONT_HEIGHT (f->display.x->font), False);
  932. #else /* ! defined (HAVE_X11) */
  933.       XPixSet (FRAME_X_WINDOW (f),
  934.            intborder,
  935.            CHAR_TO_PIXEL_ROW (f, topregion),
  936.            f->width * FONT_WIDTH (f->display.x->font),
  937.            n * FONT_HEIGHT (f->display.x->font),
  938.            f->display.x->background_pixel);
  939. #endif /* ! defined (HAVE_X11) */
  940.     }
  941. }
  942.  
  943. /* Perform a delete-lines operation, deleting N lines
  944.    at a vertical position curs_y.  */
  945.  
  946. static void
  947. scraplines (n)
  948.      register int n;
  949. {
  950.   int mask;
  951.   register struct frame *f = updating_frame;
  952.   int intborder = f->display.x->internal_border_width;
  953.  
  954.   if (curs_y >= flexlines)
  955.     return;
  956.  
  957. #ifndef HAVE_X11
  958.   dumpqueue ();
  959. #endif /* HAVE_X11 */
  960.  
  961.   if ((curs_y + n) >= flexlines)
  962.     {
  963.       if (flexlines >= (curs_y + 1))
  964.     {
  965. #ifdef HAVE_X11
  966.       XClearArea (x_current_display, FRAME_X_WINDOW (f), intborder,
  967.               CHAR_TO_PIXEL_ROW (f, curs_y),
  968.               f->width * FONT_WIDTH (f->display.x->font),
  969.               (flexlines - curs_y) * FONT_HEIGHT (f->display.x->font), False);
  970. #else /* ! defined (HAVE_X11) */
  971.       XPixSet (FRAME_X_WINDOW (f),
  972.            intborder, CHAR_TO_PIXEL_ROW (f, curs_y),
  973.            f->width * FONT_WIDTH (f->display.x->font),
  974.            (flexlines - curs_y) * FONT_HEIGHT (f->display.x->font),
  975.            f->display.x->background_pixel);
  976. #endif /* ! defined (HAVE_X11) */
  977.     }
  978.     }
  979.   else
  980.     {
  981. #ifdef HAVE_X11
  982.       XCopyArea (x_current_display, FRAME_X_WINDOW (f),
  983.          FRAME_X_WINDOW (f), f->display.x->normal_gc,
  984.          intborder,
  985.          CHAR_TO_PIXEL_ROW (f, curs_y + n),
  986.          f->width * FONT_WIDTH (f->display.x->font),
  987.          (flexlines - (curs_y + n)) * FONT_HEIGHT (f->display.x->font),
  988.          intborder, CHAR_TO_PIXEL_ROW (f, curs_y));
  989.       XClearArea (x_current_display, FRAME_X_WINDOW (f),
  990.           intborder,
  991.           CHAR_TO_PIXEL_ROW (f, flexlines - n),
  992.           f->width * FONT_WIDTH (f->display.x->font),
  993.           n * FONT_HEIGHT (f->display.x->font), False);
  994. #else /* ! defined (HAVE_X11) */
  995.       XMoveArea (FRAME_X_WINDOW (f),
  996.          intborder,
  997.          CHAR_TO_PIXEL_ROW (f, curs_y + n),
  998.          intborder, CHAR_TO_PIXEL_ROW (f, curs_y),
  999.          f->width * FONT_WIDTH (f->display.x->font),
  1000.          (flexlines - (curs_y + n)) * FONT_HEIGHT (f->display.x->font));
  1001.       /* Now we must process any ExposeRegion events that occur
  1002.      if the area being copied from is obscured.
  1003.      We can't let it wait because further i/d operations
  1004.      may want to copy this area to another area.  */
  1005.       x_read_exposes ();
  1006.       XPixSet (FRAME_X_WINDOW (f), intborder,
  1007.            CHAR_TO_PIXEL_ROW (f, flexlines - n),
  1008.            f->width * FONT_WIDTH (f->display.x->font),
  1009.            n * FONT_HEIGHT (f->display.x->font), f->display.x->background_pixel);
  1010. #endif /* ! defined (HAVE_X11) */
  1011.     }
  1012. }
  1013.  
  1014. /* Perform an insert-lines or delete-lines operation,
  1015.    inserting N lines or deleting -N lines at vertical position VPOS.  */
  1016.  
  1017. XTins_del_lines (vpos, n)
  1018.      int vpos, n;
  1019. {
  1020.   if (updating_frame == 0)
  1021.     abort ();
  1022.  
  1023.   /* Hide the cursor.  */
  1024.   x_display_cursor (updating_frame, 0);
  1025.  
  1026.   XTcursor_to (vpos, 0);
  1027.  
  1028.   BLOCK_INPUT;
  1029.   if (n >= 0)
  1030.     stufflines (n);
  1031.   else
  1032.     scraplines (-n);
  1033.   XFlushQueue ();
  1034.   UNBLOCK_INPUT;
  1035. }
  1036.  
  1037. /* Support routines for exposure events.  */
  1038. static void clear_cursor ();
  1039.  
  1040. /* Output into a rectangle of an X-window (for frame F)
  1041.    the characters in f->phys_lines that overlap that rectangle.
  1042.    TOP and LEFT are the position of the upper left corner of the rectangle.
  1043.    ROWS and COLS are the size of the rectangle.  */
  1044.  
  1045. static void
  1046. dumprectangle (f, left, top, cols, rows)
  1047.      struct frame *f;
  1048.      register int left, top, cols, rows;
  1049. {
  1050.   register struct frame_glyphs *active_frame = FRAME_CURRENT_GLYPHS (f);
  1051.   int cursor_cleared = 0;
  1052.   int bottom, right;
  1053.   register int y;
  1054.  
  1055.   if (FRAME_GARBAGED_P (f))
  1056.     return;
  1057.  
  1058.   /* Express rectangle as four edges, instead of position-and-size.  */
  1059.   bottom = top + rows;
  1060.   right = left + cols;
  1061.  
  1062. #ifndef HAVE_X11        /* Window manger does this for X11. */
  1063.   {
  1064.     int intborder = f->display.x->internal_border_width;
  1065.  
  1066.     /* If the rectangle includes any of the internal border area,
  1067.        redisplay the border emphasis.  */
  1068.     if (top < intborder || left < intborder
  1069.     || bottom > intborder + f->height * FONT_HEIGHT (f->display.x->font)
  1070.     || right > intborder + f->width * FONT_WIDTH (f->display.x->font))
  1071.       dumpborder (f, 0);
  1072.   }
  1073. #endif /* HAVE_X11        Window manger does this for X11. */
  1074.   
  1075.   /* Convert rectangle edges in pixels to edges in chars.
  1076.      Round down for left and top, up for right and bottom.  */
  1077.   top  = PIXEL_TO_CHAR_ROW (f, top);
  1078.   left = PIXEL_TO_CHAR_COL (f, left);
  1079.   bottom += (FONT_HEIGHT (f->display.x->font) - 1);
  1080.   right += (FONT_WIDTH (f->display.x->font) - 1);
  1081.   bottom = PIXEL_TO_CHAR_ROW (f, bottom);
  1082.   right = PIXEL_TO_CHAR_COL (f, right);
  1083.  
  1084.   /* Clip the rectangle to what can be visible.  */
  1085.   if (left < 0)
  1086.     left = 0;
  1087.   if (top < 0)
  1088.     top = 0;
  1089.   if (right > f->width)
  1090.     right = f->width;
  1091.   if (bottom > f->height)
  1092.     bottom = f->height;
  1093.  
  1094.   /* Get size in chars of the rectangle.  */
  1095.   cols = right - left;
  1096.   rows = bottom - top;
  1097.  
  1098.   /* If rectangle has zero area, return.  */
  1099.   if (rows <= 0) return;
  1100.   if (cols <= 0) return;
  1101.  
  1102.   /* Turn off the cursor if it is in the rectangle.
  1103.      We will turn it back on afterward.  */
  1104.   if ((f->phys_cursor_x >= left) && (f->phys_cursor_x < right)
  1105.       && (f->phys_cursor_y >= top) && (f->phys_cursor_y < bottom))
  1106.     {
  1107.       clear_cursor (f);
  1108.       cursor_cleared = 1;
  1109.     }
  1110.  
  1111.   /* Display the text in the rectangle, one text line at a time.  */
  1112.  
  1113.   for (y = top; y < bottom; y++)
  1114.     {
  1115.       GLYPH *line = &active_frame->glyphs[y][left];
  1116.  
  1117.       if (! active_frame->enable[y] || left > active_frame->used[y])
  1118.     continue;
  1119.  
  1120.       dumpglyphs (f,
  1121.           CHAR_TO_PIXEL_COL (f, left),
  1122.           CHAR_TO_PIXEL_ROW (f, y),
  1123.           line, min (cols, active_frame->used[y] - left),
  1124.           active_frame->highlight[y]);
  1125.     }
  1126.  
  1127.   /* Turn the cursor on if we turned it off.  */
  1128.  
  1129.   if (cursor_cleared)
  1130.     x_display_cursor (f, 1);
  1131. }
  1132.  
  1133. #ifndef HAVE_X11
  1134. /* Process all queued ExposeRegion events. */
  1135.  
  1136. static void
  1137. dumpqueue ()
  1138. {
  1139.   register int i;
  1140.   XExposeRegionEvent r;
  1141.  
  1142.   while (dequeue_event (&r, &x_expose_queue))
  1143.     {
  1144.       struct frame *f = x_window_to_frame (r.window);
  1145.       if (f->display.x->icon_desc == r.window)
  1146.     refreshicon (f);
  1147.       else
  1148.     dumprectangle (f, r.x, r.y, r.width, r.height);
  1149.     }
  1150.   XFlushQueue ();
  1151. }
  1152. #endif /* HAVE_X11 */
  1153.  
  1154. /* Process all expose events that are pending, for X10.
  1155.    Redraws the cursor if necessary on any frame that
  1156.    is not in the process of being updated with update_frame.  */
  1157.  
  1158. #ifndef HAVE_X11
  1159. static void
  1160. x_do_pending_expose ()
  1161. {
  1162.   int mask;
  1163.   struct frame *f;
  1164.   Lisp_Object tail, frame;
  1165.  
  1166.   if (expose_all_windows)
  1167.     {
  1168.       expose_all_windows = 0;
  1169.       for (tail = Vframe_list; CONSP (tail); tail = XCONS (tail)->cdr)
  1170.     {
  1171.       register int temp_width, temp_height;
  1172.       int intborder;
  1173.  
  1174.       frame = XCONS (tail)->car;
  1175.       if (XGCTYPE (frame) != Lisp_Frame)
  1176.         continue;
  1177.       f = XFRAME (frame);
  1178.       if (! FRAME_X_P (f))
  1179.         continue;
  1180.       if (!f->async_visible)
  1181.         continue;
  1182.       if (!f->display.x->needs_exposure)
  1183.         continue;
  1184.  
  1185.       intborder = f->display.x->internal_border_width;
  1186.  
  1187.       clear_cursor (f);
  1188.       XGetWindowInfo (FRAME_X_WINDOW (f), &windowinfo);
  1189.       temp_width = ((windowinfo.width - 2 * intborder
  1190.              - f->display.x->v_scroll_bar_width)
  1191.             / FONT_WIDTH (f->display.x->font));
  1192.       temp_height = ((windowinfo.height- 2 * intborder
  1193.               - f->display.x->h_scroll_bar_height)
  1194.              / FONT_HEIGHT (f->display.x->font));
  1195.       if (temp_width != f->width || temp_height != f->height)
  1196.         {
  1197.           change_frame_size (f, max (1, temp_height),
  1198.                   max (1, temp_width), 0, 1);
  1199.           x_resize_scroll_bars (f);
  1200.         }
  1201.       f->display.x->left_pos = windowinfo.x;
  1202.       f->display.x->top_pos = windowinfo.y;
  1203.       dumprectangle (f, 0, 0, PIXEL_WIDTH (f), PIXEL_HEIGHT (f));
  1204. #if 0
  1205.       dumpborder (f, 0);
  1206. #endif /* ! 0 */
  1207.       f->display.x->needs_exposure = 0;
  1208.       if (updating_frame != f)
  1209.         x_display_cursor (f, 1);
  1210.       XFlushQueue ();
  1211.     }
  1212.     }
  1213.   else
  1214.     /* Handle any individual-rectangle expose events queued
  1215.        for various windows.  */
  1216. #ifdef HAVE_X11
  1217.     ;
  1218. #else /* ! defined (HAVE_X11) */
  1219.     dumpqueue ();
  1220. #endif /* ! defined (HAVE_X11) */
  1221. }
  1222. #endif
  1223.  
  1224. #ifdef HAVE_X11
  1225. static void
  1226. frame_highlight (frame)
  1227.      struct frame *frame;
  1228. {
  1229.   /* We used to only do this if Vx_no_window_manager was non-nil, but
  1230.      the ICCCM (section 4.1.6) says that the window's border pixmap
  1231.      and border pixel are window attributes which are "private to the
  1232.      client", so we can always change it to whatever we want.  */
  1233.   BLOCK_INPUT;
  1234.   XSetWindowBorder (x_current_display, FRAME_X_WINDOW (frame),
  1235.             frame->display.x->border_pixel);
  1236.   UNBLOCK_INPUT;
  1237.   x_display_cursor (frame, 1);
  1238. }
  1239.  
  1240. static void
  1241. frame_unhighlight (frame)
  1242.      struct frame *frame;
  1243. {
  1244.   /* We used to only do this if Vx_no_window_manager was non-nil, but
  1245.      the ICCCM (section 4.1.6) says that the window's border pixmap
  1246.      and border pixel are window attributes which are "private to the
  1247.      client", so we can always change it to whatever we want.  */
  1248.   BLOCK_INPUT;
  1249.   XSetWindowBorderPixmap (x_current_display, FRAME_X_WINDOW (frame),
  1250.               frame->display.x->border_tile);
  1251.   UNBLOCK_INPUT;
  1252.   x_display_cursor (frame, 1);
  1253. }
  1254. #else /* ! defined (HAVE_X11) */
  1255. /* Dump the border-emphasis of frame F.
  1256.    If F is selected, this is a lining of the same color as the border,
  1257.    just within the border, occupying a portion of the internal border.
  1258.    If F is not selected, it is background in the same place.
  1259.    If ALWAYS is 0, don't bother explicitly drawing if it's background.
  1260.  
  1261.    ALWAYS = 1 is used when a frame becomes selected or deselected.
  1262.    In that case, we also turn the cursor off and on again
  1263.    so it will appear in the proper shape (solid if selected; else hollow.)  */
  1264.  
  1265. static void
  1266. dumpborder (f, always)
  1267.      struct frame *f;
  1268.      int always;
  1269. {
  1270.   int thickness = f->display.x->internal_border_width / 2;
  1271.   int width = PIXEL_WIDTH (f);
  1272.   int height = PIXEL_HEIGHT (f);
  1273.   int pixel;
  1274.  
  1275.   if (f != selected_frame)
  1276.     {
  1277.       if (!always)
  1278.     return;
  1279.  
  1280.       pixel = f->display.x->background_pixel;
  1281.     }
  1282.   else
  1283.     {
  1284.       pixel = f->display.x->border_pixel;
  1285.     }
  1286.  
  1287.   XPixSet (FRAME_X_WINDOW (f), 0, 0, width, thickness, pixel);
  1288.   XPixSet (FRAME_X_WINDOW (f), 0, 0, thickness, height, pixel);
  1289.   XPixSet (FRAME_X_WINDOW (f), 0, height - thickness, width,
  1290.        thickness, pixel);
  1291.   XPixSet (FRAME_X_WINDOW (f), width - thickness, 0, thickness,
  1292.        height, pixel);
  1293.  
  1294.   if (always)
  1295.     x_display_cursor (f, 1);
  1296. }
  1297. #endif /* ! defined (HAVE_X11) */
  1298.  
  1299. static void XTframe_rehighlight ();
  1300.  
  1301. /* The focus has changed.  Update the frames as necessary to reflect
  1302.    the new situation.  Note that we can't change the selected frame
  1303.    here, because the lisp code we are interrupting might become confused.
  1304.    Each event gets marked with the frame in which it occurred, so the
  1305.    lisp code can tell when the switch took place by examining the events.  */
  1306.  
  1307. static void
  1308. x_new_focus_frame (frame)
  1309.      struct frame *frame;
  1310. {
  1311.   struct frame *old_focus = x_focus_frame;
  1312.   int events_enqueued = 0;
  1313.  
  1314.   if (frame != x_focus_frame)
  1315.     {
  1316.       /* Set this before calling other routines, so that they see 
  1317.      the correct value of x_focus_frame.  */
  1318.       x_focus_frame = frame;
  1319.  
  1320.       if (old_focus && old_focus->auto_lower)
  1321.     x_lower_frame (old_focus);
  1322.  
  1323. #if 0
  1324.       selected_frame = frame;
  1325.       XSET (XWINDOW (selected_frame->selected_window)->frame,
  1326.         Lisp_Frame, selected_frame);
  1327.       Fselect_window (selected_frame->selected_window);
  1328.       choose_minibuf_frame ();
  1329. #endif /* ! 0 */
  1330.  
  1331.       if (x_focus_frame && x_focus_frame->auto_raise)
  1332.     x_raise_frame (x_focus_frame);
  1333.     }
  1334.  
  1335.   XTframe_rehighlight ();
  1336. }
  1337.  
  1338.  
  1339. /* The focus has changed, or we have redirected a frame's focus to
  1340.    another frame (this happens when a frame uses a surrogate
  1341.    minibuffer frame).  Shift the highlight as appropriate.  */
  1342. static void
  1343. XTframe_rehighlight ()
  1344. {
  1345.   struct frame *old_highlight = x_highlight_frame;
  1346.  
  1347.   if (x_focus_frame)
  1348.     {
  1349.       x_highlight_frame =
  1350.     ((XGCTYPE (FRAME_FOCUS_FRAME (x_focus_frame)) == Lisp_Frame)
  1351.      ? XFRAME (FRAME_FOCUS_FRAME (x_focus_frame))
  1352.      : x_focus_frame);
  1353.       if (! FRAME_LIVE_P (x_highlight_frame))
  1354.     {
  1355.       FRAME_FOCUS_FRAME (x_focus_frame) = Qnil;
  1356.       x_highlight_frame = x_focus_frame;
  1357.     }
  1358.     }
  1359.   else
  1360.     x_highlight_frame = 0;
  1361.  
  1362.   if (x_highlight_frame != old_highlight)
  1363.     {
  1364.       if (old_highlight)
  1365.     frame_unhighlight (old_highlight);
  1366.       if (x_highlight_frame)
  1367.     frame_highlight (x_highlight_frame);
  1368.     }
  1369. }
  1370.  
  1371. /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
  1372.  
  1373. /* Which modifier keys are on which modifier bits?
  1374.  
  1375.    With each keystroke, X returns eight bits indicating which modifier
  1376.    keys were held down when the key was pressed.  The interpretation
  1377.    of the top five modifier bits depends on what keys are attached
  1378.    to them.  If the Meta_L and Meta_R keysyms are on mod5, then mod5
  1379.    is the meta bit.
  1380.    
  1381.    x_meta_mod_mask is a mask containing the bits used for the meta key.
  1382.    It may have more than one bit set, if more than one modifier bit
  1383.    has meta keys on it.  Basically, if EVENT is a KeyPress event,
  1384.    the meta key is pressed if (EVENT.state & x_meta_mod_mask) != 0.  
  1385.  
  1386.    x_shift_lock_mask is LockMask if the XK_Shift_Lock keysym is on the
  1387.    lock modifier bit, or zero otherwise.  Non-alphabetic keys should
  1388.    only be affected by the lock modifier bit if XK_Shift_Lock is in
  1389.    use; XK_Caps_Lock should only affect alphabetic keys.  With this
  1390.    arrangement, the lock modifier should shift the character if
  1391.    (EVENT.state & x_shift_lock_mask) != 0.  */
  1392. static int x_meta_mod_mask, x_shift_lock_mask;
  1393.  
  1394. /* These are like x_meta_mod_mask, but for different modifiers.  */
  1395. static int x_alt_mod_mask, x_super_mod_mask, x_hyper_mod_mask;
  1396.  
  1397. /* Initialize mode_switch_bit and modifier_meaning.  */
  1398. static void
  1399. x_find_modifier_meanings ()
  1400. {
  1401.   int min_code, max_code;
  1402.   KeySym *syms;
  1403.   int syms_per_code;
  1404.   XModifierKeymap *mods;
  1405.  
  1406.   x_meta_mod_mask = 0;
  1407.   x_shift_lock_mask = 0;
  1408.   x_alt_mod_mask = 0;
  1409.   x_super_mod_mask = 0;
  1410.   x_hyper_mod_mask = 0;
  1411.   
  1412. #ifdef HAVE_X11R4
  1413.   XDisplayKeycodes (x_current_display, &min_code, &max_code);
  1414. #else
  1415.   min_code = x_current_display->min_keycode;
  1416.   max_code = x_current_display->max_keycode;
  1417. #endif
  1418.  
  1419.   syms = XGetKeyboardMapping (x_current_display,
  1420.                   min_code, max_code - min_code + 1,
  1421.                   &syms_per_code);
  1422.   mods = XGetModifierMapping (x_current_display);
  1423.  
  1424.   /* Scan the modifier table to see which modifier bits the Meta and 
  1425.      Alt keysyms are on.  */
  1426.   {
  1427.     int row, col;    /* The row and column in the modifier table. */
  1428.  
  1429.     for (row = 3; row < 8; row++)
  1430.       for (col = 0; col < mods->max_keypermod; col++)
  1431.     {
  1432.       KeyCode code =
  1433.         mods->modifiermap[(row * mods->max_keypermod) + col];
  1434.  
  1435.       /* Are any of this keycode's keysyms a meta key?  */
  1436.       {
  1437.         int code_col;
  1438.  
  1439.         for (code_col = 0; code_col < syms_per_code; code_col++)
  1440.           {
  1441.         int sym = syms[((code - min_code) * syms_per_code) + code_col];
  1442.  
  1443.         switch (sym)
  1444.           {
  1445.           case XK_Meta_L:
  1446.           case XK_Meta_R:
  1447.             x_meta_mod_mask |= (1 << row);
  1448.             break;
  1449.  
  1450.           case XK_Alt_L:
  1451.           case XK_Alt_R:
  1452.             x_alt_mod_mask |= (1 << row);
  1453.             break;
  1454.  
  1455.           case XK_Hyper_L:
  1456.           case XK_Hyper_R:
  1457.             x_hyper_mod_mask |= (1 << row);
  1458.             break;
  1459.  
  1460.           case XK_Super_L:
  1461.           case XK_Super_R:
  1462.             x_super_mod_mask |= (1 << row);
  1463.             break;
  1464.  
  1465.           case XK_Shift_Lock:
  1466.             /* Ignore this if it's not on the lock modifier.  */
  1467.             if ((1 << row) == LockMask)
  1468.               x_shift_lock_mask = LockMask;
  1469.             break;
  1470.           }
  1471.           }
  1472.       }
  1473.     }
  1474.   }
  1475.  
  1476.   /* If we couldn't find any meta keys, accept any alt keys as meta keys.  */
  1477.   if (! x_meta_mod_mask)
  1478.     {
  1479.       x_meta_mod_mask = x_alt_mod_mask;
  1480.       x_alt_mod_mask = 0;
  1481.     }
  1482.  
  1483.   /* If some keys are both alt and meta,
  1484.      make them just meta, not alt.  */
  1485.   if (x_alt_mod_mask & x_meta_mod_mask)
  1486.     {
  1487.       x_alt_mod_mask &= ~x_meta_mod_mask;
  1488.     }
  1489.   
  1490.   XFree ((char *) syms);
  1491.   XFreeModifiermap (mods);
  1492. }
  1493.  
  1494.  
  1495. /* Convert between the modifier bits X uses and the modifier bits
  1496.    Emacs uses.  */
  1497. static unsigned int
  1498. x_x_to_emacs_modifiers (state)
  1499.      unsigned int state;
  1500. {
  1501.   return (  ((state & (ShiftMask | x_shift_lock_mask)) ? shift_modifier : 0)
  1502.       | ((state & ControlMask)               ? ctrl_modifier  : 0)
  1503.       | ((state & x_meta_mod_mask)               ? meta_modifier  : 0)
  1504.       | ((state & x_alt_mod_mask)               ? alt_modifier  : 0)
  1505.       | ((state & x_super_mod_mask)               ? super_modifier  : 0)
  1506.       | ((state & x_hyper_mod_mask)               ? hyper_modifier  : 0));
  1507. }
  1508.  
  1509. static unsigned int
  1510. x_emacs_to_x_modifiers (state)
  1511.      unsigned int state;
  1512. {
  1513.   return (  ((state & alt_modifier)        ? x_alt_mod_mask   : 0)
  1514.       | ((state & super_modifier)        ? x_super_mod_mask : 0)
  1515.       | ((state & hyper_modifier)        ? x_hyper_mod_mask : 0)
  1516.       | ((state & shift_modifier)        ? ShiftMask        : 0)
  1517.       | ((state & ctrl_modifier)        ? ControlMask      : 0)
  1518.       | ((state & meta_modifier)        ? x_meta_mod_mask  : 0));
  1519. }
  1520.  
  1521. /* Return true iff KEYSYM is a vendor-specific keysym that we should
  1522.    return as a function key.  If you add a keysym to this, you should
  1523.    make sure that the tables make_lispy_event uses contain a suitable
  1524.    name for it.  */
  1525. static int
  1526. x_is_vendor_fkey (sym)
  1527.      KeySym sym;
  1528. {
  1529.   return 0
  1530. #ifdef DXK_Remove
  1531.     || (sym == DXK_Remove)
  1532. #endif
  1533.       ;
  1534. }
  1535.  
  1536.  
  1537. /* Mouse clicks and mouse movement.  Rah.  */
  1538. #ifdef HAVE_X11
  1539.  
  1540. /* Given a pixel position (PIX_X, PIX_Y) on the frame F, return
  1541.    glyph co-ordinates in (*X, *Y).  Set *BOUNDS to the rectangle
  1542.    that the glyph at X, Y occupies, if BOUNDS != 0.  */
  1543. static void
  1544. pixel_to_glyph_coords (f, pix_x, pix_y, x, y, bounds)
  1545.      FRAME_PTR f;
  1546.      register unsigned int pix_x, pix_y;
  1547.      register int *x, *y;
  1548.      XRectangle *bounds;
  1549. {
  1550.   pix_x = PIXEL_TO_CHAR_COL (f, pix_x);
  1551.   pix_y = PIXEL_TO_CHAR_ROW (f, pix_y);
  1552.  
  1553.   if (bounds)
  1554.     {
  1555.       bounds->width  = FONT_WIDTH  (f->display.x->font);
  1556.       bounds->height = FONT_HEIGHT (f->display.x->font);
  1557.       bounds->x = CHAR_TO_PIXEL_COL (f, pix_x);
  1558.       bounds->y = CHAR_TO_PIXEL_ROW (f, pix_y);
  1559.     }
  1560.  
  1561.   if (pix_x < 0) pix_x = 0;
  1562.   else if (pix_x > f->width) pix_x = f->width;
  1563.  
  1564.   if (pix_y < 0) pix_y = 0;
  1565.   else if (pix_y > f->height) pix_y = f->height;
  1566.  
  1567.   *x = pix_x;
  1568.   *y = pix_y;
  1569. }
  1570.  
  1571. /* Any buttons grabbed. */
  1572. unsigned int x_mouse_grabbed;
  1573.  
  1574. /* Prepare a mouse-event in *RESULT for placement in the input queue.
  1575.  
  1576.    If the event is a button press, then note that we have grabbed
  1577.    the mouse.  */
  1578.  
  1579. static Lisp_Object
  1580. construct_mouse_click (result, event, f)
  1581.      struct input_event *result;
  1582.      XButtonEvent *event;
  1583.      struct frame *f;
  1584. {
  1585.   /* Make the event type no_event; we'll change that when we decide
  1586.      otherwise.  */
  1587.   result->kind = mouse_click;
  1588.   XSET (result->code, Lisp_Int, event->button - Button1);
  1589.   result->timestamp = event->time;
  1590.   result->modifiers = (x_x_to_emacs_modifiers (event->state)
  1591.                | (event->type == ButtonRelease
  1592.               ? up_modifier 
  1593.               : down_modifier));
  1594.  
  1595.   /* Notice if the mouse is still grabbed.  */
  1596.   if (event->type == ButtonPress)
  1597.     {
  1598.       if (! x_mouse_grabbed)
  1599.     Vmouse_depressed = Qt;
  1600.       x_mouse_grabbed |= (1 << event->button);
  1601.     }
  1602.   else if (event->type == ButtonRelease)
  1603.     {
  1604.       x_mouse_grabbed &= ~(1 << event->button);
  1605.       if (!x_mouse_grabbed)
  1606.     Vmouse_depressed = Qnil;
  1607.     }
  1608.  
  1609.   {
  1610.     int row, column;
  1611.  
  1612.     pixel_to_glyph_coords (f, event->x, event->y, &column, &row, NULL);
  1613.     XFASTINT (result->x) = column;
  1614.     XFASTINT (result->y) = row;
  1615.     XSET (result->frame_or_window, Lisp_Frame, f);
  1616.   }
  1617. }
  1618.  
  1619.  
  1620. /* Mouse movement.  Rah.
  1621.  
  1622.    In order to avoid asking for motion events and then throwing most
  1623.    of them away or busy-polling the server for mouse positions, we ask
  1624.    the server for pointer motion hints.  This means that we get only
  1625.    one event per group of mouse movements.  "Groups" are delimited by
  1626.    other kinds of events (focus changes and button clicks, for
  1627.    example), or by XQueryPointer calls; when one of these happens, we
  1628.    get another MotionNotify event the next time the mouse moves.  This
  1629.    is at least as efficient as getting motion events when mouse
  1630.    tracking is on, and I suspect only negligibly worse when tracking
  1631.    is off.
  1632.  
  1633.    The silly O'Reilly & Associates Nutshell guides barely document
  1634.    pointer motion hints at all (I think you have to infer how they
  1635.    work from an example), and the description of XQueryPointer doesn't
  1636.    mention that calling it causes you to get another motion hint from
  1637.    the server, which is very important.  */
  1638.  
  1639. /* Where the mouse was last time we reported a mouse event.  */
  1640. static FRAME_PTR last_mouse_frame;
  1641. static XRectangle last_mouse_glyph;
  1642.  
  1643. /* The scroll bar in which the last X motion event occurred.
  1644.  
  1645.    If the last X motion event occurred in a scroll bar, we set this
  1646.    so XTmouse_position can know whether to report a scroll bar motion or
  1647.    an ordinary motion.
  1648.  
  1649.    If the last X motion event didn't occur in a scroll bar, we set this
  1650.    to Qnil, to tell XTmouse_position to return an ordinary motion event.  */
  1651. static Lisp_Object last_mouse_scroll_bar;
  1652.  
  1653. /* This is a hack.  We would really prefer that XTmouse_position would
  1654.    return the time associated with the position it returns, but there
  1655.    doesn't seem to be any way to wrest the timestamp from the server
  1656.    along with the position query.  So, we just keep track of the time
  1657.    of the last movement we received, and return that in hopes that
  1658.    it's somewhat accurate.  */
  1659. static Time last_mouse_movement_time;
  1660.  
  1661. /* Function to report a mouse movement to the mainstream Emacs code.
  1662.    The input handler calls this.
  1663.  
  1664.    We have received a mouse movement event, which is given in *event.
  1665.    If the mouse is over a different glyph than it was last time, tell
  1666.    the mainstream emacs code by setting mouse_moved.  If not, ask for
  1667.    another motion event, so we can check again the next time it moves.  */
  1668. static void
  1669. note_mouse_movement (frame, event)
  1670.      FRAME_PTR frame;
  1671.      XMotionEvent *event;
  1672.  
  1673. {
  1674.   last_mouse_movement_time = event->time;
  1675.  
  1676.   /* Has the mouse moved off the glyph it was on at the last sighting?  */
  1677.   if (event->x < last_mouse_glyph.x
  1678.       || event->x >= last_mouse_glyph.x + last_mouse_glyph.width
  1679.       || event->y < last_mouse_glyph.y
  1680.       || event->y >= last_mouse_glyph.y + last_mouse_glyph.height)
  1681.     {
  1682.       mouse_moved = 1;
  1683.       last_mouse_scroll_bar = Qnil;
  1684.     }
  1685.   else
  1686.     {
  1687.       /* It's on the same glyph.  Call XQueryPointer so we'll get an
  1688.      event the next time the mouse moves and we can see if it's
  1689.      *still* on the same glyph.  */
  1690.       int dummy;
  1691.       
  1692.       XQueryPointer (event->display, event->window,
  1693.              (Window *) &dummy, (Window *) &dummy,
  1694.              &dummy, &dummy, &dummy, &dummy,
  1695.              (unsigned int *) &dummy);
  1696.     }
  1697. }
  1698.  
  1699. static struct scroll_bar *x_window_to_scroll_bar ();
  1700. static void x_scroll_bar_report_motion ();
  1701.  
  1702. /* Return the current position of the mouse.
  1703.  
  1704.    If the mouse movement started in a scroll bar, set *f, *bar_window,
  1705.    and *part to the frame, window, and scroll bar part that the mouse
  1706.    is over.  Set *x and *y to the portion and whole of the mouse's
  1707.    position on the scroll bar.
  1708.  
  1709.    If the mouse movement started elsewhere, set *f to the frame the
  1710.    mouse is on, *bar_window to nil, and *x and *y to the character cell
  1711.    the mouse is over.
  1712.  
  1713.    Set *time to the server timestamp for the time at which the mouse
  1714.    was at this position.
  1715.  
  1716.    Don't store anything if we don't have a valid set of values to report.
  1717.  
  1718.    This clears the mouse_moved flag, so we can wait for the next mouse
  1719.    movement.  This also calls XQueryPointer, which will cause the
  1720.    server to give us another MotionNotify when the mouse moves
  1721.    again. */
  1722.  
  1723. static void
  1724. XTmouse_position (f, bar_window, part, x, y, time)
  1725.      FRAME_PTR *f;
  1726.      Lisp_Object *bar_window;
  1727.      enum scroll_bar_part *part;
  1728.      Lisp_Object *x, *y;
  1729.      unsigned long *time;
  1730. {
  1731.   FRAME_PTR f1;
  1732.  
  1733.   BLOCK_INPUT;
  1734.  
  1735.   if (! NILP (last_mouse_scroll_bar))
  1736.     x_scroll_bar_report_motion (f, bar_window, part, x, y, time);
  1737.   else
  1738.     {
  1739.       Window root;
  1740.       int root_x, root_y;
  1741.  
  1742.       Window dummy_window;
  1743.       int dummy;
  1744.  
  1745.       mouse_moved = 0;
  1746.       last_mouse_scroll_bar = Qnil;
  1747.  
  1748.       /* Figure out which root window we're on.  */
  1749.       XQueryPointer (x_current_display,
  1750.              DefaultRootWindow (x_current_display),
  1751.  
  1752.              /* The root window which contains the pointer.  */
  1753.              &root,
  1754.  
  1755.              /* Trash which we can't trust if the pointer is on
  1756.             a different screen.  */
  1757.              &dummy_window,
  1758.  
  1759.              /* The position on that root window.  */
  1760.              &root_x, &root_y, 
  1761.  
  1762.              /* More trash we can't trust.  */
  1763.              &dummy, &dummy,
  1764.  
  1765.              /* Modifier keys and pointer buttons, about which
  1766.             we don't care.  */
  1767.              (unsigned int *) &dummy);
  1768.  
  1769.       /* Now we have a position on the root; find the innermost window
  1770.      containing the pointer.  */
  1771.       {
  1772.     Window win, child;
  1773.     int win_x, win_y;
  1774.     int parent_x, parent_y;
  1775.  
  1776.     win = root;
  1777.     for (;;)
  1778.       {
  1779.         XTranslateCoordinates (x_current_display,
  1780.                    
  1781.                    /* From-window, to-window.  */
  1782.                    root, win,
  1783.  
  1784.                    /* From-position, to-position.  */
  1785.                    root_x, root_y, &win_x, &win_y,
  1786.  
  1787.                    /* Child of win.  */
  1788.                    &child);
  1789.  
  1790.         if (child == None)
  1791.           break;
  1792.  
  1793.         win = child;
  1794.         parent_x = win_x;
  1795.         parent_y = win_y;
  1796.       }
  1797.  
  1798.     /* Now we know that:
  1799.        win is the innermost window containing the pointer
  1800.        (XTC says it has no child containing the pointer),
  1801.        win_x and win_y are the pointer's position in it
  1802.        (XTC did this the last time through), and
  1803.        parent_x and parent_y are the pointer's position in win's parent.
  1804.        (They are what win_x and win_y were when win was child.
  1805.        If win is the root window, it has no parent, and
  1806.        parent_{x,y} are invalid, but that's okay, because we'll
  1807.        never use them in that case.)  */
  1808.  
  1809.     /* Is win one of our frames?  */
  1810.     f1 = x_window_to_frame (win);
  1811.       
  1812.     /* If not, is it one of our scroll bars?  */
  1813.     if (! f1)
  1814.       {
  1815.         struct scroll_bar *bar = x_window_to_scroll_bar (win);
  1816.  
  1817.         if (bar)
  1818.           {
  1819.         f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  1820.         win_x = parent_x;
  1821.         win_y = parent_y;
  1822.           }
  1823.       }
  1824.  
  1825.     if (f1)
  1826.       {
  1827.         /* Ok, we found a frame.  Convert from pixels to characters
  1828.            and store all the values.  */
  1829.  
  1830.         pixel_to_glyph_coords (f1, win_x, win_y, &win_x, &win_y,
  1831.                    &last_mouse_glyph);
  1832.  
  1833.         *bar_window = Qnil;
  1834.         *part = 0;
  1835.         *f = f1;
  1836.         XSET (*x, Lisp_Int, win_x);
  1837.         XSET (*y, Lisp_Int, win_y);
  1838.         *time = last_mouse_movement_time;
  1839.       }
  1840.       }
  1841.     }
  1842.  
  1843.   UNBLOCK_INPUT;
  1844. }
  1845.  
  1846. #else /* ! defined (HAVE_X11) */
  1847. #define XEvent XKeyPressedEvent
  1848. #endif /* ! defined (HAVE_X11) */
  1849.  
  1850. /* Scroll bar support.  */
  1851.  
  1852. /* Given an X window ID, find the struct scroll_bar which manages it.
  1853.    This can be called in GC, so we have to make sure to strip off mark
  1854.    bits.  */
  1855. static struct scroll_bar *
  1856. x_window_to_scroll_bar (window_id)
  1857.      Window window_id;
  1858. {
  1859.   Lisp_Object tail, frame;
  1860.  
  1861.   for (tail = Vframe_list;
  1862.        XGCTYPE (tail) == Lisp_Cons;
  1863.        tail = XCONS (tail)->cdr)
  1864.     {
  1865.       Lisp_Object frame = XCONS (tail)->car;
  1866.       Lisp_Object bar, condemned;
  1867.  
  1868.       /* All elements of Vframe_list should be frames.  */
  1869.       if (XGCTYPE (frame) != Lisp_Frame)
  1870.     abort ();
  1871.  
  1872.       /* Scan this frame's scroll bar list for a scroll bar with the
  1873.          right window ID.  */
  1874.       condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
  1875.       for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
  1876.        /* This trick allows us to search both the ordinary and
  1877.               condemned scroll bar lists with one loop.  */
  1878.        ! GC_NILP (bar) || (bar = condemned,
  1879.                    condemned = Qnil,
  1880.                    ! GC_NILP (bar));
  1881.        bar = XSCROLL_BAR(bar)->next)
  1882.     if (SCROLL_BAR_X_WINDOW (XSCROLL_BAR (bar)) == window_id)
  1883.       return XSCROLL_BAR (bar);
  1884.     }
  1885.  
  1886.   return 0;
  1887. }
  1888.  
  1889. /* Open a new X window to serve as a scroll bar, and return the
  1890.    scroll bar vector for it.  */
  1891. static struct scroll_bar *
  1892. x_scroll_bar_create (window, top, left, width, height)
  1893.      struct window *window;
  1894.      int top, left, width, height;
  1895. {
  1896.   FRAME_PTR frame = XFRAME (WINDOW_FRAME (window));
  1897.   struct scroll_bar *bar =
  1898.     XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
  1899.  
  1900.   BLOCK_INPUT;
  1901.  
  1902.   {
  1903.     XSetWindowAttributes a;
  1904.     unsigned long mask;
  1905.  
  1906.     a.background_pixel = frame->display.x->background_pixel;
  1907.     a.event_mask = (ButtonPressMask | ButtonReleaseMask
  1908.             | ButtonMotionMask | PointerMotionHintMask
  1909.             | ExposureMask);
  1910.     a.cursor = x_vertical_scroll_bar_cursor;
  1911.  
  1912.     mask = (CWBackPixel | CWEventMask | CWCursor);
  1913.  
  1914.     SET_SCROLL_BAR_X_WINDOW
  1915.       (bar, 
  1916.        XCreateWindow (x_current_display, FRAME_X_WINDOW (frame),
  1917.  
  1918.               /* Position and size of scroll bar.  */
  1919.               left, top, width, height,
  1920.  
  1921.               /* Border width, depth, class, and visual.  */
  1922.               0, CopyFromParent, CopyFromParent, CopyFromParent,
  1923.  
  1924.               /* Attributes.  */
  1925.               mask, &a));
  1926.   }
  1927.  
  1928.   XSET (bar->window, Lisp_Window, window);
  1929.   XSET (bar->top,    Lisp_Int, top);
  1930.   XSET (bar->left,   Lisp_Int, left);
  1931.   XSET (bar->width,  Lisp_Int, width);
  1932.   XSET (bar->height, Lisp_Int, height);
  1933.   XSET (bar->start,  Lisp_Int, 0);
  1934.   XSET (bar->end,    Lisp_Int, 0);
  1935.   bar->dragging = Qnil;
  1936.  
  1937.   /* Add bar to its frame's list of scroll bars.  */
  1938.   bar->next = FRAME_SCROLL_BARS (frame);
  1939.   bar->prev = Qnil;
  1940.   XSET (FRAME_SCROLL_BARS (frame), Lisp_Vector, bar);
  1941.   if (! NILP (bar->next))
  1942.     XSET (XSCROLL_BAR (bar->next)->prev, Lisp_Vector, bar);
  1943.  
  1944.   XMapWindow (x_current_display, SCROLL_BAR_X_WINDOW (bar));
  1945.  
  1946.   UNBLOCK_INPUT;
  1947.  
  1948.   return bar;
  1949. }
  1950.  
  1951. /* Draw BAR's handle in the proper position.
  1952.    If the handle is already drawn from START to END, don't bother
  1953.    redrawing it, unless REBUILD is non-zero; in that case, always
  1954.    redraw it.  (REBUILD is handy for drawing the handle after expose
  1955.    events.)  
  1956.  
  1957.    Normally, we want to constrain the start and end of the handle to
  1958.    fit inside its rectangle, but if the user is dragging the scroll bar
  1959.    handle, we want to let them drag it down all the way, so that the
  1960.    bar's top is as far down as it goes; otherwise, there's no way to
  1961.    move to the very end of the buffer.  */
  1962. static void
  1963. x_scroll_bar_set_handle (bar, start, end, rebuild)
  1964.      struct scroll_bar *bar;
  1965.      int start, end;
  1966.      int rebuild;
  1967. {
  1968.   int dragging = ! NILP (bar->dragging);
  1969.   Window w = SCROLL_BAR_X_WINDOW (bar);
  1970.   GC gc = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))->display.x->normal_gc;
  1971.  
  1972.   /* If the display is already accurate, do nothing.  */
  1973.   if (! rebuild
  1974.       && start == XINT (bar->start)
  1975.       && end == XINT (bar->end))
  1976.     return;
  1977.  
  1978.   BLOCK_INPUT;
  1979.  
  1980.   {
  1981.     int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (XINT (bar->width));
  1982.     int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (XINT (bar->height));
  1983.     int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (XINT (bar->height));
  1984.  
  1985.     /* Make sure the values are reasonable, and try to preserve
  1986.        the distance between start and end.  */
  1987.     {
  1988.       int length = end - start;
  1989.  
  1990.       if (start < 0)
  1991.     start = 0;
  1992.       else if (start > top_range)
  1993.     start = top_range;
  1994.       end = start + length;
  1995.  
  1996.       if (end < start)
  1997.     end = start;
  1998.       else if (end > top_range && ! dragging)
  1999.     end = top_range;
  2000.     }
  2001.  
  2002.     /* Store the adjusted setting in the scroll bar.  */
  2003.     XSET (bar->start, Lisp_Int, start);
  2004.     XSET (bar->end, Lisp_Int, end);
  2005.  
  2006.     /* Clip the end position, just for display.  */
  2007.     if (end > top_range)
  2008.       end = top_range;
  2009.  
  2010.     /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
  2011.        below top positions, to make sure the handle is always at least
  2012.        that many pixels tall.  */
  2013.     end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
  2014.  
  2015.     /* Draw the empty space above the handle.  Note that we can't clear
  2016.        zero-height areas; that means "clear to end of window."  */
  2017.     if (0 < start)
  2018.       XClearArea (x_current_display, w,
  2019.  
  2020.           /* x, y, width, height, and exposures.  */
  2021.           VERTICAL_SCROLL_BAR_LEFT_BORDER,
  2022.           VERTICAL_SCROLL_BAR_TOP_BORDER,
  2023.           inside_width, start,
  2024.           False);
  2025.  
  2026.     /* Draw the handle itself.  */
  2027.     XFillRectangle (x_current_display, w, gc,
  2028.  
  2029.             /* x, y, width, height */
  2030.             VERTICAL_SCROLL_BAR_LEFT_BORDER,
  2031.             VERTICAL_SCROLL_BAR_TOP_BORDER + start,
  2032.             inside_width, end - start);
  2033.  
  2034.  
  2035.     /* Draw the empty space below the handle.  Note that we can't
  2036.        clear zero-height areas; that means "clear to end of window." */
  2037.     if (end < inside_height)
  2038.       XClearArea (x_current_display, w,
  2039.  
  2040.           /* x, y, width, height, and exposures.  */
  2041.           VERTICAL_SCROLL_BAR_LEFT_BORDER,
  2042.           VERTICAL_SCROLL_BAR_TOP_BORDER + end,
  2043.           inside_width, inside_height - end,
  2044.           False);
  2045.  
  2046.   }
  2047.  
  2048.   UNBLOCK_INPUT;
  2049. }
  2050.  
  2051. /* Move a scroll bar around on the screen, to accommodate changing
  2052.    window configurations.  */
  2053. static void
  2054. x_scroll_bar_move (bar, top, left, width, height)
  2055.      struct scroll_bar *bar;
  2056.      int top, left, width, height;
  2057. {
  2058.   BLOCK_INPUT;
  2059.  
  2060.   {
  2061.     XWindowChanges wc;
  2062.     unsigned int mask = 0;
  2063.  
  2064.     wc.x = left;
  2065.     wc.y = top;
  2066.     wc.width = width;
  2067.     wc.height = height;
  2068.  
  2069.     if (left != XINT (bar->left))    mask |= CWX;
  2070.     if (top != XINT (bar->top))        mask |= CWY;
  2071.     if (width != XINT (bar->width))    mask |= CWWidth;
  2072.     if (height != XINT (bar->height))    mask |= CWHeight;
  2073.     
  2074.     if (mask)
  2075.       XConfigureWindow (x_current_display, SCROLL_BAR_X_WINDOW (bar),
  2076.             mask, &wc);
  2077.   }
  2078.  
  2079.   XSET (bar->left,   Lisp_Int, left);
  2080.   XSET (bar->top,    Lisp_Int, top);
  2081.   XSET (bar->width,  Lisp_Int, width);
  2082.   XSET (bar->height, Lisp_Int, height);
  2083.  
  2084.   UNBLOCK_INPUT;
  2085. }
  2086.  
  2087. /* Destroy the X window for BAR, and set its Emacs window's scroll bar
  2088.    to nil.  */
  2089. static void
  2090. x_scroll_bar_remove (bar)
  2091.      struct scroll_bar *bar;
  2092. {
  2093.   FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  2094.  
  2095.   BLOCK_INPUT;
  2096.  
  2097.   /* Destroy the window.  */
  2098.   XDestroyWindow (x_current_display, SCROLL_BAR_X_WINDOW (bar));
  2099.  
  2100.   /* Disassociate this scroll bar from its window.  */
  2101.   XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
  2102.  
  2103.   UNBLOCK_INPUT;
  2104. }
  2105.  
  2106. /* Set the handle of the vertical scroll bar for WINDOW to indicate
  2107.    that we are displaying PORTION characters out of a total of WHOLE
  2108.    characters, starting at POSITION.  If WINDOW has no scroll bar,
  2109.    create one.  */
  2110. static void
  2111. XTset_vertical_scroll_bar (window, portion, whole, position)
  2112.      struct window *window;
  2113.      int portion, whole, position;
  2114. {
  2115.   FRAME_PTR f = XFRAME (WINDOW_FRAME (window));
  2116.   int top = XINT (window->top);
  2117.   int left = WINDOW_VERTICAL_SCROLL_BAR_COLUMN (window);
  2118.   int height = WINDOW_VERTICAL_SCROLL_BAR_HEIGHT (window);
  2119.  
  2120.   /* Where should this scroll bar be, pixelwise?  */
  2121.   int pixel_top  = CHAR_TO_PIXEL_ROW (f, top);
  2122.   int pixel_left = CHAR_TO_PIXEL_COL (f, left);
  2123.   int pixel_width = VERTICAL_SCROLL_BAR_PIXEL_WIDTH (f);
  2124.   int pixel_height = VERTICAL_SCROLL_BAR_PIXEL_HEIGHT (f, height);
  2125.  
  2126.   struct scroll_bar *bar;
  2127.  
  2128.   /* Does the scroll bar exist yet?  */
  2129.   if (NILP (window->vertical_scroll_bar))
  2130.     bar = x_scroll_bar_create (window,
  2131.                   pixel_top, pixel_left,
  2132.                   pixel_width, pixel_height);
  2133.   else
  2134.     {
  2135.       /* It may just need to be moved and resized.  */
  2136.       bar = XSCROLL_BAR (window->vertical_scroll_bar);
  2137.       x_scroll_bar_move (bar, pixel_top, pixel_left, pixel_width, pixel_height);
  2138.     }
  2139.  
  2140.   /* Set the scroll bar's current state, unless we're currently being
  2141.      dragged.  */
  2142.   if (NILP (bar->dragging))
  2143.     {
  2144.       int top_range =
  2145.     VERTICAL_SCROLL_BAR_TOP_RANGE (pixel_height);
  2146.  
  2147.       if (whole == 0)
  2148.     x_scroll_bar_set_handle (bar, 0, top_range, 0);
  2149.       else
  2150.     {
  2151.       int start = ((double) position * top_range) / whole;
  2152.       int end = ((double) (position + portion) * top_range) / whole;
  2153.  
  2154.       x_scroll_bar_set_handle (bar, start, end, 0);
  2155.     }
  2156.     }
  2157.  
  2158.   XSET (window->vertical_scroll_bar, Lisp_Vector, bar);
  2159. }
  2160.  
  2161.  
  2162. /* The following three hooks are used when we're doing a thorough
  2163.    redisplay of the frame.  We don't explicitly know which scroll bars
  2164.    are going to be deleted, because keeping track of when windows go
  2165.    away is a real pain - "Can you say set-window-configuration, boys
  2166.    and girls?"  Instead, we just assert at the beginning of redisplay
  2167.    that *all* scroll bars are to be removed, and then save a scroll bar
  2168.    from the fiery pit when we actually redisplay its window.  */
  2169.  
  2170. /* Arrange for all scroll bars on FRAME to be removed at the next call
  2171.    to `*judge_scroll_bars_hook'.  A scroll bar may be spared if
  2172.    `*redeem_scroll_bar_hook' is applied to its window before the judgement.  */
  2173. static void 
  2174. XTcondemn_scroll_bars (frame)
  2175.      FRAME_PTR frame;
  2176. {
  2177.   /* The condemned list should be empty at this point; if it's not,
  2178.      then the rest of Emacs isn't using the condemn/redeem/judge
  2179.      protocol correctly.  */
  2180.   if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
  2181.     abort ();
  2182.  
  2183.   /* Move them all to the "condemned" list.  */
  2184.   FRAME_CONDEMNED_SCROLL_BARS (frame) = FRAME_SCROLL_BARS (frame);
  2185.   FRAME_SCROLL_BARS (frame) = Qnil;
  2186. }
  2187.  
  2188. /* Unmark WINDOW's scroll bar for deletion in this judgement cycle.
  2189.    Note that WINDOW isn't necessarily condemned at all.  */
  2190. static void
  2191. XTredeem_scroll_bar (window)
  2192.      struct window *window;
  2193. {
  2194.   struct scroll_bar *bar;
  2195.  
  2196.   /* We can't redeem this window's scroll bar if it doesn't have one.  */
  2197.   if (NILP (window->vertical_scroll_bar))
  2198.     abort ();
  2199.  
  2200.   bar = XSCROLL_BAR (window->vertical_scroll_bar);
  2201.  
  2202.   /* Unlink it from the condemned list.  */
  2203.   {
  2204.     FRAME_PTR f = XFRAME (WINDOW_FRAME (window));
  2205.  
  2206.     if (NILP (bar->prev))
  2207.       {
  2208.     /* If the prev pointer is nil, it must be the first in one of
  2209.            the lists.  */
  2210.     if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
  2211.       /* It's not condemned.  Everything's fine.  */
  2212.       return;
  2213.     else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
  2214.              window->vertical_scroll_bar))
  2215.       FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
  2216.     else
  2217.       /* If its prev pointer is nil, it must be at the front of
  2218.              one or the other!  */
  2219.       abort ();
  2220.       }
  2221.     else
  2222.       XSCROLL_BAR (bar->prev)->next = bar->next;
  2223.  
  2224.     if (! NILP (bar->next))
  2225.       XSCROLL_BAR (bar->next)->prev = bar->prev;
  2226.  
  2227.     bar->next = FRAME_SCROLL_BARS (f);
  2228.     bar->prev = Qnil;
  2229.     XSET (FRAME_SCROLL_BARS (f), Lisp_Vector, bar);
  2230.     if (! NILP (bar->next))
  2231.       XSET (XSCROLL_BAR (bar->next)->prev, Lisp_Vector, bar);
  2232.   }
  2233. }
  2234.  
  2235. /* Remove all scroll bars on FRAME that haven't been saved since the
  2236.    last call to `*condemn_scroll_bars_hook'.  */
  2237. static void
  2238. XTjudge_scroll_bars (f)
  2239.      FRAME_PTR f;
  2240. {
  2241.   Lisp_Object bar, next;
  2242.  
  2243.   bar = FRAME_CONDEMNED_SCROLL_BARS (f);
  2244.  
  2245.   /* Clear out the condemned list now so we won't try to process any
  2246.      more events on the hapless scroll bars.  */
  2247.   FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
  2248.  
  2249.   for (; ! NILP (bar); bar = next)
  2250.     {
  2251.       struct scroll_bar *b = XSCROLL_BAR (bar);
  2252.  
  2253.       x_scroll_bar_remove (b);
  2254.  
  2255.       next = b->next;
  2256.       b->next = b->prev = Qnil;
  2257.     }
  2258.  
  2259.   /* Now there should be no references to the condemned scroll bars,
  2260.      and they should get garbage-collected.  */
  2261. }
  2262.  
  2263.  
  2264. /* Handle an Expose or GraphicsExpose event on a scroll bar.
  2265.  
  2266.    This may be called from a signal handler, so we have to ignore GC
  2267.    mark bits.  */
  2268. static void
  2269. x_scroll_bar_expose (bar, event)
  2270.      struct scroll_bar *bar;
  2271.      XEvent *event;
  2272. {
  2273.   Window w = SCROLL_BAR_X_WINDOW (bar);
  2274.   GC gc = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))->display.x->normal_gc;
  2275.  
  2276.   BLOCK_INPUT;
  2277.  
  2278.   x_scroll_bar_set_handle (bar, XINT (bar->start), XINT (bar->end), 1);
  2279.  
  2280.   /* Draw a one-pixel border just inside the edges of the scroll bar. */
  2281.   XDrawRectangle (x_current_display, w, gc,
  2282.  
  2283.           /* x, y, width, height */
  2284.           0, 0, XINT (bar->width) - 1, XINT (bar->height) - 1);
  2285.  
  2286.   /* Draw another line to make the extra-thick border on the right.  */
  2287.   XFillRectangle (x_current_display, w, gc,
  2288.  
  2289.           /* x, y, width, height */
  2290.           XINT (bar->width) - 2, 1, 1, XINT (bar->height) - 2);
  2291.  
  2292.   UNBLOCK_INPUT;
  2293. }
  2294.  
  2295. /* Handle a mouse click on the scroll bar BAR.  If *EMACS_EVENT's kind
  2296.    is set to something other than no_event, it is enqueued.
  2297.  
  2298.    This may be called from a signal handler, so we have to ignore GC
  2299.    mark bits.  */
  2300. static void
  2301. x_scroll_bar_handle_click (bar, event, emacs_event)
  2302.      struct scroll_bar *bar;
  2303.      XEvent *event;
  2304.      struct input_event *emacs_event;
  2305. {
  2306.   if (XGCTYPE (bar->window) != Lisp_Window)
  2307.     abort ();
  2308.  
  2309.   emacs_event->kind = scroll_bar_click;
  2310.   XSET (emacs_event->code, Lisp_Int, event->xbutton.button - Button1);
  2311.   emacs_event->modifiers =
  2312.     (x_x_to_emacs_modifiers (event->xbutton.state)
  2313.      | (event->type == ButtonRelease
  2314.     ? up_modifier
  2315.     : down_modifier));
  2316.   emacs_event->frame_or_window = bar->window;
  2317.   emacs_event->timestamp = event->xbutton.time;
  2318.   {
  2319.     int internal_height =
  2320.       VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (XINT (bar->height));
  2321.     int top_range =
  2322.       VERTICAL_SCROLL_BAR_TOP_RANGE (XINT (bar->height));
  2323.     int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
  2324.  
  2325.     if (y < 0) y = 0;
  2326.     if (y > top_range) y = top_range;
  2327.  
  2328.     if (y < XINT (bar->start))
  2329.       emacs_event->part = scroll_bar_above_handle;
  2330.     else if (y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
  2331.       emacs_event->part = scroll_bar_handle;
  2332.     else
  2333.       emacs_event->part = scroll_bar_below_handle;
  2334.  
  2335.     /* Just because the user has clicked on the handle doesn't mean
  2336.        they want to drag it.  Lisp code needs to be able to decide
  2337.        whether or not we're dragging.  */
  2338. #if 0
  2339.     /* If the user has just clicked on the handle, record where they're
  2340.        holding it.  */
  2341.     if (event->type == ButtonPress
  2342.     && emacs_event->part == scroll_bar_handle)
  2343.       XSET (bar->dragging, Lisp_Int, y - XINT (bar->start));
  2344. #endif
  2345.  
  2346.     /* If the user has released the handle, set it to its final position.  */
  2347.     if (event->type == ButtonRelease
  2348.     && ! NILP (bar->dragging))
  2349.       {
  2350.     int new_start = y - XINT (bar->dragging);
  2351.     int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
  2352.  
  2353.     x_scroll_bar_set_handle (bar, new_start, new_end, 0);
  2354.     bar->dragging = Qnil;
  2355.       }
  2356.  
  2357.     /* Same deal here as the other #if 0.  */
  2358. #if 0
  2359.     /* Clicks on the handle are always reported as occurring at the top of 
  2360.        the handle.  */
  2361.     if (emacs_event->part == scroll_bar_handle)
  2362.       emacs_event->x = bar->start;
  2363.     else
  2364.       XSET (emacs_event->x, Lisp_Int, y);
  2365. #else
  2366.     XSET (emacs_event->x, Lisp_Int, y);
  2367. #endif
  2368.  
  2369.     XSET (emacs_event->y, Lisp_Int, top_range);
  2370.   }
  2371. }
  2372.  
  2373. /* Handle some mouse motion while someone is dragging the scroll bar.
  2374.  
  2375.    This may be called from a signal handler, so we have to ignore GC
  2376.    mark bits.  */
  2377. static void
  2378. x_scroll_bar_note_movement (bar, event)
  2379.      struct scroll_bar *bar;
  2380.      XEvent *event;
  2381. {
  2382.   last_mouse_movement_time = event->xmotion.time;
  2383.  
  2384.   mouse_moved = 1;
  2385.   XSET (last_mouse_scroll_bar, Lisp_Vector, bar);
  2386.  
  2387.   /* If we're dragging the bar, display it.  */
  2388.   if (! GC_NILP (bar->dragging))
  2389.     {
  2390.       /* Where should the handle be now?  */
  2391.       int new_start = event->xmotion.y - XINT (bar->dragging);
  2392.  
  2393.       if (new_start != XINT (bar->start))
  2394.     {
  2395.       int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
  2396.     
  2397.       x_scroll_bar_set_handle (bar, new_start, new_end, 0);
  2398.     }
  2399.     }
  2400.  
  2401.   /* Call XQueryPointer so we'll get an event the next time the mouse
  2402.      moves and we can see *still* on the same position.  */
  2403.   {
  2404.     int dummy;
  2405.       
  2406.     XQueryPointer (event->xmotion.display, event->xmotion.window,
  2407.            (Window *) &dummy, (Window *) &dummy,
  2408.            &dummy, &dummy, &dummy, &dummy,
  2409.            (unsigned int *) &dummy);
  2410.   }
  2411. }
  2412.  
  2413. /* Return information to the user about the current position of the mouse
  2414.    on the scroll bar.  */
  2415. static void
  2416. x_scroll_bar_report_motion (f, bar_window, part, x, y, time)
  2417.      FRAME_PTR *f;
  2418.      Lisp_Object *bar_window;
  2419.      enum scroll_bar_part *part;
  2420.      Lisp_Object *x, *y;
  2421.      unsigned long *time;
  2422. {
  2423.   struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
  2424.   int win_x, win_y;
  2425.   Window dummy_window;
  2426.   int dummy_coord;
  2427.   unsigned int dummy_mask;
  2428.  
  2429.   BLOCK_INPUT;
  2430.  
  2431.   /* Get the mouse's position relative to the scroll bar window, and
  2432.      report that.  */
  2433.   if (! XQueryPointer (x_current_display,
  2434.                SCROLL_BAR_X_WINDOW (bar),
  2435.  
  2436.                /* Root, child, root x and root y.  */
  2437.                &dummy_window, &dummy_window,
  2438.                &dummy_coord, &dummy_coord,
  2439.  
  2440.                /* Position relative to scroll bar.  */
  2441.                &win_x, &win_y,
  2442.  
  2443.                /* Mouse buttons and modifier keys.  */
  2444.                &dummy_mask))
  2445.     *f = 0;
  2446.   else
  2447.     {
  2448.       int inside_height
  2449.     = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (XINT (bar->height));
  2450.       int top_range
  2451.     = VERTICAL_SCROLL_BAR_TOP_RANGE     (XINT (bar->height));
  2452.  
  2453.       win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
  2454.  
  2455.       if (! NILP (bar->dragging))
  2456.     win_y -= XINT (bar->dragging);
  2457.  
  2458.       if (win_y < 0)
  2459.     win_y = 0;
  2460.       if (win_y > top_range)
  2461.     win_y = top_range;
  2462.  
  2463.       *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  2464.       *bar_window = bar->window;
  2465.  
  2466.       if (! NILP (bar->dragging))
  2467.     *part = scroll_bar_handle;
  2468.       else if (win_y < XINT (bar->start))
  2469.     *part = scroll_bar_above_handle;
  2470.       else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
  2471.     *part = scroll_bar_handle;
  2472.       else
  2473.     *part = scroll_bar_below_handle;
  2474.  
  2475.       XSET (*x, Lisp_Int, win_y);
  2476.       XSET (*y, Lisp_Int, top_range);
  2477.  
  2478.       mouse_moved = 0;
  2479.       last_mouse_scroll_bar = Qnil;
  2480.     }
  2481.  
  2482.   *time = last_mouse_movement_time;
  2483.  
  2484.   UNBLOCK_INPUT;
  2485. }
  2486.  
  2487.  
  2488. /* The screen has been cleared so we may have changed foreground or
  2489.    background colors, and the scroll bars may need to be redrawn.
  2490.    Clear out the scroll bars, and ask for expose events, so we can
  2491.    redraw them.  */
  2492.  
  2493. x_scroll_bar_clear (f)
  2494.      FRAME_PTR f;
  2495. {
  2496.   Lisp_Object bar;
  2497.  
  2498.   for (bar = FRAME_SCROLL_BARS (f);
  2499.        XTYPE (bar) == Lisp_Vector;
  2500.        bar = XSCROLL_BAR (bar)->next)
  2501.     XClearArea (x_current_display, SCROLL_BAR_X_WINDOW (XSCROLL_BAR (bar)),
  2502.         0, 0, 0, 0, True);
  2503. }
  2504.  
  2505.  
  2506.  
  2507. /* The main X event-reading loop - XTread_socket.  */
  2508.  
  2509. /* Timestamp of enter window event.  This is only used by XTread_socket,
  2510.    but we have to put it out here, since static variables within functions
  2511.    sometimes don't work.  */
  2512. static Time enter_timestamp;
  2513.  
  2514. /* This holds the state XLookupString needs to implement dead keys
  2515.    and other tricks known as "compose processing".  _X Window System_ 
  2516.    says that a portable program can't use this, but Stephen Gildea assures
  2517.    me that letting the compiler initialize it to zeros will work okay.
  2518.  
  2519.    This must be defined outside of XTread_socket, for the same reasons
  2520.    given for enter_timestamp, above.  */
  2521. static XComposeStatus compose_status;
  2522.  
  2523. /* Communication with window managers. */
  2524. Atom Xatom_wm_protocols;
  2525.  
  2526. /* Kinds of protocol things we may receive. */
  2527. Atom Xatom_wm_take_focus;
  2528. Atom Xatom_wm_save_yourself;
  2529. Atom Xatom_wm_delete_window;
  2530.  
  2531. /* Other WM communication */
  2532. Atom Xatom_wm_configure_denied;      /* When our config request is denied */
  2533. Atom Xatom_wm_window_moved;      /* When the WM moves us. */
  2534.  
  2535. /* Window manager communication.  */
  2536. Atom Xatom_wm_change_state;
  2537.  
  2538. /* Record the last 100 characters stored
  2539.    to help debug the loss-of-chars-during-GC problem.  */
  2540. int temp_index;
  2541. short temp_buffer[100];
  2542.  
  2543. /* Read events coming from the X server.
  2544.    This routine is called by the SIGIO handler.
  2545.    We return as soon as there are no more events to be read.
  2546.  
  2547.    Events representing keys are stored in buffer BUFP,
  2548.    which can hold up to NUMCHARS characters.
  2549.    We return the number of characters stored into the buffer,
  2550.    thus pretending to be `read'.
  2551.  
  2552.    WAITP is nonzero if we should block until input arrives.
  2553.    EXPECTED is nonzero if the caller knows input is available.  */
  2554.  
  2555. int
  2556. XTread_socket (sd, bufp, numchars, waitp, expected)
  2557.      register int sd;
  2558.      register struct input_event *bufp;
  2559.      register int numchars;
  2560.      int waitp;
  2561.      int expected;
  2562. {
  2563.   int count = 0;
  2564.   int nbytes = 0;
  2565.   int mask;
  2566.   int items_pending;        /* How many items are in the X queue. */
  2567.   XEvent event;
  2568.   struct frame *f;
  2569.   int event_found = 0;
  2570.   int prefix;
  2571.   Lisp_Object part;
  2572.  
  2573.   if (interrupt_input_blocked)
  2574.     {
  2575.       interrupt_input_pending = 1;
  2576.       return -1;
  2577.     }
  2578.  
  2579.   interrupt_input_pending = 0;
  2580.   BLOCK_INPUT;
  2581.     
  2582.   if (numchars <= 0)
  2583.     abort ();            /* Don't think this happens. */
  2584.  
  2585. #ifdef FIOSNBIO
  2586.   /* If available, Xlib uses FIOSNBIO to make the socket
  2587.      non-blocking, and then looks for EWOULDBLOCK.  If O_NDELAY is set,
  2588.      FIOSNBIO is ignored, and instead of signalling EWOULDBLOCK,
  2589.      a read returns 0, which Xlib interprets as equivalent to EPIPE. */
  2590.   fcntl (fileno (stdin), F_SETFL, 0);
  2591. #endif /* ! defined (FIOSNBIO) */
  2592.  
  2593. #ifndef SIGIO
  2594. #ifndef HAVE_SELECT
  2595.   if (! (fcntl (fileno (stdin), F_GETFL, 0) & O_NDELAY))
  2596.     {
  2597.       extern int read_alarm_should_throw;
  2598.       read_alarm_should_throw = 1;
  2599.       XPeekEvent (XDISPLAY &event);
  2600.       read_alarm_should_throw = 0;
  2601.     }
  2602. #endif /* HAVE_SELECT */
  2603. #endif /* SIGIO */
  2604.  
  2605.   while (XStuffPending () != 0)
  2606.     {
  2607.       XNextEvent (XDISPLAY &event);
  2608.       event_found = 1;
  2609.  
  2610.       switch (event.type)
  2611.     {
  2612. #ifdef HAVE_X11
  2613.     case ClientMessage:
  2614.       {
  2615.         if (event.xclient.message_type == Xatom_wm_protocols
  2616.         && event.xclient.format == 32)
  2617.           {
  2618.         if (event.xclient.data.l[0] == Xatom_wm_take_focus)
  2619.           {
  2620.             f = x_window_to_frame (event.xclient.window);
  2621.             if (f)
  2622.               x_focus_on_frame (f);
  2623.             /* Not certain about handling scroll bars here */
  2624.           }
  2625.         else if (event.xclient.data.l[0] == Xatom_wm_save_yourself)
  2626.           {
  2627.             /* Save state modify the WM_COMMAND property to
  2628.                something which can reinstate us. This notifies
  2629.                the session manager, who's looking for such a
  2630.                PropertyNotify.  Can restart processing when
  2631.                a keyboard or mouse event arrives. */
  2632.             if (numchars > 0)
  2633.               {
  2634.               }
  2635.           }
  2636.         else if (event.xclient.data.l[0] == Xatom_wm_delete_window)
  2637.           {
  2638.             struct frame *f = x_window_to_frame (event.xclient.window);
  2639.  
  2640.             if (f)
  2641.               if (numchars > 0)
  2642.             {
  2643.             }
  2644.           }
  2645.           }
  2646.         else if (event.xclient.message_type == Xatom_wm_configure_denied)
  2647.           {
  2648.           }
  2649.         else if (event.xclient.message_type == Xatom_wm_window_moved)
  2650.           {
  2651.         int new_x, new_y;
  2652.  
  2653.         new_x = event.xclient.data.s[0];
  2654.         new_y = event.xclient.data.s[1];
  2655.           }
  2656.       }
  2657.       break;
  2658.  
  2659. #ifdef NEW_SELECTIONS
  2660.     case SelectionNotify:
  2661.       x_handle_selection_notify (&event);
  2662.       break;
  2663. #endif
  2664.  
  2665.     case SelectionClear:    /* Someone has grabbed ownership. */
  2666. #ifdef NEW_SELECTIONS
  2667.       {
  2668.         XSelectionClearEvent *eventp = (XSelectionClearEvent *) &event;
  2669.  
  2670.         if (numchars == 0)
  2671.           abort ();
  2672.  
  2673.         bufp->kind = selection_clear_event;
  2674.         SELECTION_EVENT_DISPLAY (bufp) = eventp->display;
  2675.         SELECTION_EVENT_SELECTION (bufp) = eventp->selection;
  2676.         SELECTION_EVENT_TIME (bufp) = eventp->time;
  2677.         bufp++;
  2678.  
  2679.         count += 1;
  2680.         numchars -= 1;
  2681.       }
  2682. #else
  2683.       x_disown_selection (event.xselectionclear.window,
  2684.                   event.xselectionclear.selection,
  2685.                   event.xselectionclear.time);
  2686. #endif
  2687.       break;
  2688.  
  2689.     case SelectionRequest:    /* Someone wants our selection. */
  2690. #ifdef NEW_SELECTIONS
  2691.       {
  2692.         XSelectionRequestEvent *eventp = (XSelectionRequestEvent *) &event;
  2693.  
  2694.         if (numchars == 0)
  2695.           abort ();
  2696.  
  2697.         bufp->kind = selection_request_event;
  2698.         SELECTION_EVENT_DISPLAY (bufp) = eventp->display;
  2699.         SELECTION_EVENT_REQUESTOR (bufp) = eventp->requestor;
  2700.         SELECTION_EVENT_SELECTION (bufp) = eventp->selection;
  2701.         SELECTION_EVENT_TARGET (bufp) = eventp->target;
  2702.         SELECTION_EVENT_PROPERTY (bufp) = eventp->property;
  2703.         SELECTION_EVENT_TIME (bufp) = eventp->time;
  2704.         bufp++;
  2705.  
  2706.         count += 1;
  2707.         numchars -= 1;
  2708.       }
  2709. #else
  2710.       x_answer_selection_request (event);
  2711. #endif
  2712.       break;
  2713.  
  2714.     case PropertyNotify:
  2715. #ifdef NEW_SELECTIONS
  2716.       x_handle_property_notify (&event);
  2717. #else
  2718.       /* If we're being told about a root window property, then it's
  2719.          a cut buffer change.  */
  2720.       if (event.xproperty.window == ROOT_WINDOW)
  2721.         x_invalidate_cut_buffer_cache (&event.xproperty);
  2722.  
  2723.       /* Otherwise, we're probably handling an incremental
  2724.              selection transmission.  */
  2725.       else
  2726.         {
  2727.           /* If we were to do this synchronously, there'd be no worry
  2728.          about re-selecting. */
  2729.           x_send_incremental (event);
  2730.         }
  2731. #endif
  2732.       break;
  2733.  
  2734.     case ReparentNotify:
  2735.       f = x_window_to_frame (event.xreparent.window);
  2736.       if (f)
  2737.         f->display.x->parent_desc = event.xreparent.parent;
  2738.       break;
  2739.  
  2740.     case Expose:
  2741.       f = x_window_to_frame (event.xexpose.window);
  2742.       if (f)
  2743.         {
  2744.           if (f->async_visible == 0)
  2745.         {
  2746.           f->async_visible = 1;
  2747.           f->async_iconified = 0;
  2748.           SET_FRAME_GARBAGED (f);
  2749.         }
  2750.           else
  2751.         {
  2752.           dumprectangle (x_window_to_frame (event.xexpose.window),
  2753.                  event.xexpose.x, event.xexpose.y,
  2754.                  event.xexpose.width, event.xexpose.height);
  2755.         }
  2756.         }
  2757.       else
  2758.         {
  2759.           struct scroll_bar *bar
  2760.         = x_window_to_scroll_bar (event.xexpose.window);
  2761.  
  2762.           if (bar)
  2763.         x_scroll_bar_expose (bar, &event);
  2764.         }
  2765.       break;
  2766.  
  2767.     case GraphicsExpose:    /* This occurs when an XCopyArea's
  2768.                   source area was obscured or not
  2769.                   available.*/
  2770.       f = x_window_to_frame (event.xgraphicsexpose.drawable);
  2771.       if (f)
  2772.         {
  2773.           dumprectangle (f,
  2774.                  event.xgraphicsexpose.x, event.xgraphicsexpose.y,
  2775.                  event.xgraphicsexpose.width,
  2776.                  event.xgraphicsexpose.height);
  2777.         }
  2778.       break;
  2779.  
  2780.     case NoExpose:        /* This occurs when an XCopyArea's
  2781.                   source area was completely
  2782.                   available */
  2783.       break;
  2784. #else /* ! defined (HAVE_X11) */
  2785.     case ExposeWindow:
  2786.       if (event.subwindow != 0)
  2787.         break;        /* duplicate event */
  2788.       f = x_window_to_frame (event.window);
  2789.       if (event.window == f->display.x->icon_desc)
  2790.         {
  2791.           refreshicon (f);
  2792.           f->async_iconified = 1;
  2793.         }
  2794.       if (event.window == FRAME_X_WINDOW (f))
  2795.         {
  2796.           /* Say must check all windows' needs_exposure flags.  */
  2797.           expose_all_windows = 1;
  2798.           f->display.x->needs_exposure = 1;
  2799.           f->async_visible = 1;
  2800.         }
  2801.       break;
  2802.  
  2803.     case ExposeRegion:
  2804.       if (event.subwindow != 0)
  2805.         break;        /* duplicate event */
  2806.       f = x_window_to_frame (event.window);
  2807.       if (event.window == f->display.x->icon_desc)
  2808.         {
  2809.           refreshicon (f);
  2810.           break;
  2811.         }
  2812.       /* If window already needs full redraw, ignore this rectangle.  */
  2813.       if (expose_all_windows && f->display.x->needs_exposure)
  2814.         break;
  2815.       /* Put the event on the queue of rectangles to redraw.  */
  2816.       if (enqueue_event (&event, &x_expose_queue))
  2817.         /* If it is full, we can't record the rectangle,
  2818.            so redraw this entire window.  */
  2819.         {
  2820.           /* Say must check all windows' needs_exposure flags.  */
  2821.           expose_all_windows = 1;
  2822.           f->display.x->needs_exposure = 1;
  2823.         }
  2824.       break;
  2825.  
  2826.     case ExposeCopy:
  2827.       /* This should happen only when we are expecting it,
  2828.          in x_read_exposes.  */
  2829.       abort ();
  2830. #endif /* ! defined (HAVE_X11) */
  2831.  
  2832. #ifdef HAVE_X11
  2833.     case UnmapNotify:
  2834.       f = x_window_to_frame (event.xunmap.window);
  2835.       if (f)        /* F may no longer exist if
  2836.                    the frame was deleted.  */
  2837.         {
  2838.           /* While a frame is unmapped, display generation is
  2839.          disabled; you don't want to spend time updating a
  2840.          display that won't ever be seen.  */
  2841.           f->async_visible = 0;
  2842.           /* The window manager never makes a window invisible
  2843.          ("withdrawn"); all it does is switch between visible
  2844.          and iconified.  Frames get into the invisible state
  2845.          only through x_make_frame_invisible.  */
  2846.           if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
  2847.         f->async_iconified = 1;
  2848.         }
  2849.       break;
  2850.  
  2851.     case MapNotify:
  2852.       f = x_window_to_frame (event.xmap.window);
  2853.       if (f)
  2854.         {
  2855.           f->async_visible = 1;
  2856.           f->async_iconified = 0;
  2857.  
  2858.           /* wait_reading_process_input will notice this and update
  2859.          the frame's display structures.  */
  2860.           SET_FRAME_GARBAGED (f);
  2861.         }
  2862.       break;
  2863.  
  2864.       /* Turn off processing if we become fully obscured. */
  2865.     case VisibilityNotify:
  2866.       break;
  2867.  
  2868. #else /* ! defined (HAVE_X11) */
  2869.     case UnmapWindow:
  2870.       f = x_window_to_frame (event.window);
  2871.       if (event.window == f->display.x->icon_desc)
  2872.         f->async_iconified = 0;
  2873.       if (event.window == FRAME_X_WINDOW (f))
  2874.         f->async_visible = 0;
  2875.       break;
  2876. #endif /* ! defined (HAVE_X11) */
  2877.  
  2878. #ifdef HAVE_X11
  2879.     case KeyPress:
  2880.       f = x_window_to_frame (event.xkey.window);
  2881.  
  2882.       if (f != 0)
  2883.         {
  2884.           KeySym keysym, orig_keysym;
  2885.           char copy_buffer[80];
  2886.           int modifiers;
  2887.  
  2888.           event.xkey.state
  2889.         |= x_emacs_to_x_modifiers (extra_keyboard_modifiers);
  2890.           modifiers = event.xkey.state;
  2891.  
  2892.           /* This will have to go some day...  */
  2893.  
  2894.           /* make_lispy_event turns chars into control chars.
  2895.          Don't do it here because XLookupString is too eager.  */
  2896.           event.xkey.state &= ~ControlMask;
  2897.           nbytes =
  2898.         XLookupString (&event.xkey, copy_buffer, 80, &keysym,
  2899.                    &compose_status);
  2900.  
  2901.           /* Strip off the vendor-specific keysym bit, and take a shot
  2902.          at recognizing the codes.  HP servers have extra keysyms
  2903.          that fit into the MiscFunctionKey category.  */
  2904.           orig_keysym = keysym;
  2905.           keysym &= ~(1<<28);
  2906.  
  2907.           if (numchars > 1)
  2908.         {
  2909.           if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
  2910.                || keysym == XK_Delete
  2911.                || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
  2912.                || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
  2913. #ifdef HPUX
  2914.                /* This recognizes the "extended function keys".
  2915.               It seems there's no cleaner way.
  2916.               Test IsModifierKey to avoid handling mode_switch
  2917.               incorrectly.  */
  2918.                || ((unsigned) (keysym) >= XK_Select
  2919.                && (unsigned)(keysym) < XK_KP_Space)
  2920. #endif
  2921.                || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
  2922.                || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
  2923.                || x_is_vendor_fkey (orig_keysym))
  2924.               && ! IsModifierKey (orig_keysym)) /* wherever */
  2925.             {
  2926.               if (temp_index == sizeof temp_buffer / sizeof (short))
  2927.             temp_index = 0;
  2928.               temp_buffer[temp_index++] = keysym;
  2929.               bufp->kind = non_ascii_keystroke;
  2930.               XSET (bufp->code, Lisp_Int, (unsigned) keysym - 0xff00);
  2931.               XSET (bufp->frame_or_window, Lisp_Frame, f);
  2932.               bufp->modifiers = x_x_to_emacs_modifiers (modifiers);
  2933.               bufp->timestamp = event.xkey.time;
  2934.               bufp++;
  2935.               count++;
  2936.               numchars--;
  2937.             }
  2938.           else if (numchars > nbytes)
  2939.             {
  2940.               register int i;
  2941.  
  2942.               for (i = 0; i < nbytes; i++)
  2943.             {
  2944.               if (temp_index == sizeof temp_buffer / sizeof (short))
  2945.                 temp_index = 0;
  2946.               temp_buffer[temp_index++] = copy_buffer[i];
  2947.               bufp->kind = ascii_keystroke;
  2948.               XSET (bufp->code, Lisp_Int, copy_buffer[i]);
  2949.               XSET (bufp->frame_or_window, Lisp_Frame, f);
  2950.               bufp->modifiers = x_x_to_emacs_modifiers (modifiers);
  2951.               bufp->timestamp = event.xkey.time;
  2952.               bufp++;
  2953.             }
  2954.  
  2955.               count += nbytes;
  2956.               numchars -= nbytes;
  2957.             }
  2958.           else
  2959.             abort ();
  2960.         }
  2961.           else
  2962.         abort ();
  2963.         }
  2964.       break;
  2965. #else /* ! defined (HAVE_X11) */
  2966.     case KeyPressed:
  2967.       {
  2968.         register char *where_mapping;
  2969.  
  2970.         f = x_window_to_frame (event.window);
  2971.         /* Ignore keys typed on icon windows.  */
  2972.         if (f != 0 && event.window == f->display.x->icon_desc)
  2973.           break;
  2974.         where_mapping = XLookupMapping (&event, &nbytes);
  2975.         /* Nasty fix for arrow keys */
  2976.         if (!nbytes && IsCursorKey (event.detail & 0xff))
  2977.           {
  2978.         switch (event.detail & 0xff)
  2979.           {
  2980.           case KC_CURSOR_LEFT:
  2981.             where_mapping = "\002";
  2982.             break;
  2983.           case KC_CURSOR_RIGHT:
  2984.             where_mapping = "\006";
  2985.             break;
  2986.           case KC_CURSOR_UP:
  2987.             where_mapping = "\020";
  2988.             break;
  2989.           case KC_CURSOR_DOWN:
  2990.             where_mapping = "\016";
  2991.             break;
  2992.           }
  2993.         nbytes = 1;
  2994.           }
  2995.         if (numchars - nbytes > 0)
  2996.           {
  2997.         register int i;
  2998.  
  2999.         for (i = 0; i < nbytes; i++)
  3000.           {
  3001.             bufp->kind = ascii_keystroke;
  3002.             XSET (bufp->code, Lisp_Int, where_mapping[i]);
  3003.             XSET (bufp->time, Lisp_Int, event.xkey.time);
  3004.             XSET (bufp->frame_or_window, Lisp_Frame, f);
  3005.             bufp++;
  3006.           }
  3007.         count += nbytes;
  3008.         numchars -= nbytes;
  3009.           }
  3010.       }
  3011.       break;
  3012. #endif /* ! defined (HAVE_X11) */
  3013.  
  3014. #ifdef HAVE_X11
  3015.  
  3016.       /* Here's a possible interpretation of the whole
  3017.          FocusIn-EnterNotify FocusOut-LeaveNotify mess.  If you get a
  3018.          FocusIn event, you have to get a FocusOut event before you
  3019.          relinquish the focus.  If you haven't received a FocusIn event,
  3020.          then a mere LeaveNotify is enough to free you.  */
  3021.  
  3022.     case EnterNotify:
  3023.       f = x_window_to_frame (event.xcrossing.window);
  3024.  
  3025.       if (event.xcrossing.focus)        /* Entered Window */
  3026.         {
  3027.           /* Avoid nasty pop/raise loops. */
  3028.           if (f && (!(f->auto_raise)
  3029.             || !(f->auto_lower)
  3030.             || (event.xcrossing.time - enter_timestamp) > 500))
  3031.         {
  3032.           x_new_focus_frame (f);
  3033.           enter_timestamp = event.xcrossing.time;
  3034.         }
  3035.         }
  3036.       else if (f == x_focus_frame)
  3037.         x_new_focus_frame (0);
  3038.  
  3039.       break;
  3040.  
  3041.     case FocusIn:
  3042.       f = x_window_to_frame (event.xfocus.window);
  3043.       if (event.xfocus.detail != NotifyPointer) 
  3044.         x_focus_event_frame = f;
  3045.       if (f)
  3046.         x_new_focus_frame (f);
  3047.       break;
  3048.  
  3049.  
  3050.     case LeaveNotify:
  3051.       f = x_window_to_frame (event.xcrossing.window);
  3052.  
  3053.       if (event.xcrossing.focus)
  3054.         {
  3055.           if (! x_focus_event_frame)
  3056.         x_new_focus_frame (0);
  3057.           else
  3058.         x_new_focus_frame (f);
  3059.         }
  3060.       else 
  3061.         {
  3062.           if (f == x_focus_event_frame)
  3063.         x_focus_event_frame = 0;
  3064.           if (f == x_focus_frame)
  3065.         x_new_focus_frame (0);
  3066.         }
  3067.       break;
  3068.  
  3069.     case FocusOut:
  3070.       f = x_window_to_frame (event.xfocus.window);
  3071.       if (event.xfocus.detail != NotifyPointer
  3072.           && f == x_focus_event_frame)
  3073.         x_focus_event_frame = 0;
  3074.       if (f && f == x_focus_frame)
  3075.         x_new_focus_frame (0);
  3076.       break;
  3077.  
  3078. #else /* ! defined (HAVE_X11) */
  3079.  
  3080.     case EnterWindow:
  3081.       if ((event.detail & 0xFF) == 1)
  3082.         break;        /* Coming from our own subwindow */
  3083.       if (event.subwindow != 0)
  3084.         break;        /* Entering our own subwindow.  */
  3085.  
  3086.       {
  3087.         f = x_window_to_frame (event.window);
  3088.         x_mouse_frame = f;
  3089.  
  3090.         x_new_focus_frame (f);
  3091.       }
  3092.       break;
  3093.  
  3094.     case LeaveWindow:
  3095.       if ((event.detail & 0xFF) == 1)
  3096.         break;        /* Entering our own subwindow */
  3097.       if (event.subwindow != 0)
  3098.         break;        /* Leaving our own subwindow.  */
  3099.  
  3100.       x_mouse_frame = 0;
  3101.       if (x_focus_frame == 0
  3102.           && x_input_frame != 0
  3103.           && x_input_frame == x_window_to_frame (event.window)
  3104.           && event.window == FRAME_X_WINDOW (x_input_frame))
  3105.         {
  3106.           f = x_input_frame;
  3107.           x_input_frame = 0;
  3108.           if (f)
  3109.         frame_unhighlight (f);
  3110.         }
  3111.       break;
  3112. #endif /* ! defined (HAVE_X11) */
  3113.  
  3114. #ifdef HAVE_X11
  3115.     case MotionNotify:
  3116.       {
  3117.         f = x_window_to_frame (event.xmotion.window);
  3118.         if (f)
  3119.           note_mouse_movement (f, &event.xmotion);
  3120.         else
  3121.           {
  3122.         struct scroll_bar *bar =
  3123.           x_window_to_scroll_bar (event.xmotion.window);
  3124.  
  3125.         if (bar)
  3126.           x_scroll_bar_note_movement (bar, &event);
  3127.           }
  3128.       }
  3129.       break;
  3130.  
  3131.     case ConfigureNotify:
  3132.       f = x_window_to_frame (event.xconfigure.window);
  3133.       if (f)
  3134.         {
  3135.           int rows = PIXEL_TO_CHAR_HEIGHT (f, event.xconfigure.height);
  3136.           int columns = PIXEL_TO_CHAR_WIDTH (f, event.xconfigure.width);
  3137.  
  3138.           /* Even if the number of character rows and columns has
  3139.          not changed, the font size may have changed, so we need
  3140.          to check the pixel dimensions as well.  */
  3141.           if (columns != f->width
  3142.           || rows != f->height
  3143.           || event.xconfigure.width != f->display.x->pixel_width
  3144.           || event.xconfigure.height != f->display.x->pixel_height)
  3145.         {
  3146.           change_frame_size (f, rows, columns, 0, 1);
  3147.           SET_FRAME_GARBAGED (f);
  3148.         }
  3149.  
  3150.           if (! event.xconfigure.send_event)
  3151.         {
  3152.           Window win, child;
  3153.           int win_x, win_y;
  3154.  
  3155.           /* Find the position of the outside upper-left corner of
  3156.              the window, in the root coordinate system.  Don't
  3157.              refer to the parent window here; we may be processing
  3158.              this event after the window manager has changed our
  3159.              parent, but before we have reached the ReparentNotify.  */
  3160.           XTranslateCoordinates (x_current_display,
  3161.                    
  3162.                      /* From-window, to-window.  */
  3163.                      f->display.x->window_desc,
  3164.                      ROOT_WINDOW,
  3165.  
  3166.                      /* From-position, to-position.  */
  3167.                      -event.xconfigure.border_width,
  3168.                      -event.xconfigure.border_width,
  3169.                      &win_x, &win_y,
  3170.  
  3171.                      /* Child of win.  */
  3172.                      &child);
  3173.           event.xconfigure.x = win_x;
  3174.           event.xconfigure.y = win_y;
  3175.         }
  3176.  
  3177.           f->display.x->pixel_width = event.xconfigure.width;
  3178.           f->display.x->pixel_height = event.xconfigure.height;
  3179.           f->display.x->left_pos = event.xconfigure.x;
  3180.           f->display.x->top_pos = event.xconfigure.y;
  3181.         }
  3182.       break;
  3183.  
  3184.     case ButtonPress:
  3185.     case ButtonRelease:
  3186.       {
  3187.         /* If we decide we want to generate an event to be seen
  3188.            by the rest of Emacs, we put it here.  */
  3189.         struct input_event emacs_event;
  3190.         emacs_event.kind = no_event;
  3191.  
  3192.         f = x_window_to_frame (event.xbutton.window);
  3193.         if (f)
  3194.           {
  3195.         if (!x_focus_frame || (f == x_focus_frame))
  3196.           construct_mouse_click (&emacs_event,
  3197.                      &event, f);
  3198.           }
  3199.         else
  3200.           {
  3201.         struct scroll_bar *bar =
  3202.           x_window_to_scroll_bar (event.xbutton.window);
  3203.  
  3204.         if (bar)
  3205.           x_scroll_bar_handle_click (bar, &event, &emacs_event);
  3206.           }
  3207.  
  3208.         if (numchars >= 1 && emacs_event.kind != no_event)
  3209.           {
  3210.         bcopy (&emacs_event, bufp, sizeof (struct input_event));
  3211.         bufp++;
  3212.         count++;
  3213.         numchars--;
  3214.           }
  3215.       }
  3216.       break;
  3217.  
  3218. #else /* ! defined (HAVE_X11) */
  3219.     case ButtonPressed:
  3220.     case ButtonReleased:
  3221.       f = x_window_to_frame (event.window);
  3222.       if (f)
  3223.         {
  3224.           if (event.window == f->display.x->icon_desc)
  3225.         {
  3226.           x_make_frame_visible (f);
  3227.  
  3228.           if (warp_mouse_on_deiconify)
  3229.             XWarpMouse (FRAME_X_WINDOW (f), 10, 10);
  3230.           break;
  3231.         }
  3232.           if (event.window == FRAME_X_WINDOW (f))
  3233.         {
  3234.           if (f->auto_raise)
  3235.             x_raise_frame (f);
  3236.         }
  3237.         }
  3238.       enqueue_event (&event, &x_mouse_queue);
  3239.       if (numchars >= 2)
  3240.         {
  3241.           bufp->kind = ascii_keystroke;
  3242.           bufp->code = (char) 'X' & 037; /* C-x */
  3243.           XSET (bufp->frame_or_window, Lisp_Frame, f);
  3244.           XSET (bufp->time, Lisp_Int, event.xkey.time);
  3245.           bufp++;
  3246.  
  3247.           bufp->kind = ascii_keystroke;
  3248.           bufp->code = (char) 0; /* C-@ */
  3249.           XSET (bufp->frame_or_window, Lisp_Frame, f);
  3250.           XSET (bufp->time, Lisp_Int, event.xkey.time);
  3251.           bufp++;
  3252.  
  3253.           count += 2;
  3254.           numchars -= 2;
  3255.         }
  3256.       break;
  3257. #endif /* ! defined (HAVE_X11) */
  3258.  
  3259. #ifdef HAVE_X11
  3260.  
  3261.     case CirculateNotify:
  3262.       break;
  3263.     case CirculateRequest:
  3264.       break;
  3265.  
  3266. #endif /* ! defined (HAVE_X11) */
  3267.  
  3268.     case MappingNotify:
  3269.       /* Someone has changed the keyboard mapping - update the
  3270.          local cache.  */
  3271.       switch (event.xmapping.request)
  3272.         {
  3273.         case MappingModifier:
  3274.           x_find_modifier_meanings ();
  3275.           /* This is meant to fall through.  */
  3276.         case MappingKeyboard:
  3277.           XRefreshKeyboardMapping (&event.xmapping);
  3278.         }
  3279.       break;
  3280.  
  3281.     default:
  3282.       break;
  3283.     }
  3284.     }
  3285.  
  3286. #ifdef HAVE_SELECT
  3287.   if (expected && ! event_found)
  3288.     {
  3289.       /* AOJ 880406: if select returns true but XPending doesn't, it means that
  3290.      there is an EOF condition; in other words, that X has died.
  3291.      Act as if there had been a hangup. */
  3292.       int fd = ConnectionNumber (x_current_display);
  3293.       SELECT_TYPE mask;
  3294.       EMACS_TIME timeout;
  3295.  
  3296.       FD_SET(fd, &mask);
  3297.       EMACS_SET_SECS_USECS (timeout, 0, 0);
  3298.       if (0 != select (fd + 1, &mask, (long *) 0, (long *) 0, &timeout)
  3299.       && !XStuffPending ())
  3300.     kill (getpid (), SIGHUP);
  3301.     }
  3302. #endif /* ! defined (HAVE_SELECT) */
  3303.  
  3304. #ifndef HAVE_X11
  3305.   if (updating_frame == 0)
  3306.     x_do_pending_expose ();
  3307. #endif
  3308.  
  3309.   UNBLOCK_INPUT;
  3310.   return count;
  3311. }
  3312.  
  3313. #ifndef HAVE_X11
  3314. /* Read and process only Expose events
  3315.    until we get an ExposeCopy event; then return.
  3316.    This is used in insert/delete line.
  3317.    We assume input is already blocked.  */
  3318.  
  3319. static void
  3320. x_read_exposes ()
  3321. {
  3322.   struct frame *f;
  3323.   XKeyPressedEvent event;
  3324.  
  3325.   while (1)
  3326.     {
  3327.       /* while there are more events*/
  3328.       XMaskEvent (ExposeWindow | ExposeRegion | ExposeCopy, &event);
  3329.       switch (event.type)
  3330.     {
  3331.     case ExposeWindow:
  3332.       if (event.subwindow != 0)
  3333.         break;            /* duplicate event */
  3334.       f = x_window_to_frame (event.window);
  3335.       if (event.window == f->display.x->icon_desc)
  3336.         {
  3337.           refreshicon (f);
  3338.           break;
  3339.         }
  3340.       if (event.window == FRAME_X_WINDOW (f))
  3341.         {
  3342.           expose_all_windows = 1;
  3343.           f->display.x->needs_exposure = 1;
  3344.           break;
  3345.         }
  3346.       break;
  3347.  
  3348.     case ExposeRegion:
  3349.       if (event.subwindow != 0)
  3350.         break;            /* duplicate event */
  3351.       f = x_window_to_frame (event.window);
  3352.       if (event.window == f->display.x->icon_desc)
  3353.         {
  3354.           refreshicon (f);
  3355.           break;
  3356.         }
  3357.       /* If window already needs full redraw, ignore this rectangle.  */
  3358.       if (expose_all_windows && f->display.x->needs_exposure)
  3359.         break;
  3360.       /* Put the event on the queue of rectangles to redraw.  */
  3361.       if (enqueue_event (&event, &x_expose_queue))
  3362.         /* If it is full, we can't record the rectangle,
  3363.            so redraw this entire window.  */
  3364.         {
  3365.           /* Say must check all windows' needs_exposure flags.  */
  3366.           expose_all_windows = 1;
  3367.           f->display.x->needs_exposure = 1;
  3368.         }
  3369.       break;
  3370.  
  3371.     case ExposeCopy:
  3372.       return;
  3373.     }
  3374.     }
  3375. }
  3376. #endif /* HAVE_X11 */
  3377.  
  3378.  
  3379. /* Drawing the cursor.  */
  3380.  
  3381.  
  3382. /* Draw a hollow box cursor.  Don't change the inside of the box.  */
  3383.  
  3384. static void
  3385. x_draw_box (f)
  3386.      struct frame *f;
  3387. {
  3388.   int left = CHAR_TO_PIXEL_COL (f, f->cursor_x);
  3389.   int top  = CHAR_TO_PIXEL_ROW (f, f->cursor_y);
  3390.   int width = FONT_WIDTH (f->display.x->font);
  3391.   int height = FONT_HEIGHT (f->display.x->font);
  3392.  
  3393. #ifdef HAVE_X11
  3394.   XDrawRectangle (x_current_display, FRAME_X_WINDOW (f),
  3395.           f->display.x->cursor_gc,
  3396.           left, top, width - 1, height - 1);
  3397. #else /* ! defined (HAVE_X11) */
  3398.   XPixSet (FRAME_X_WINDOW (f),
  3399.        left, top, width, 1,
  3400.        f->display.x->cursor_pixel);
  3401.  
  3402.   XPixSet (FRAME_X_WINDOW (f),
  3403.        left, top, 1, height,
  3404.        f->display.x->cursor_pixel);
  3405.  
  3406.   XPixSet (FRAME_X_WINDOW (f),
  3407.        left+width-1, top, 1, height,
  3408.        f->display.x->cursor_pixel);
  3409.  
  3410.   XPixSet (FRAME_X_WINDOW (f),
  3411.        left, top+height-1, width, 1,
  3412.        f->display.x->cursor_pixel);
  3413. #endif /* ! defined (HAVE_X11) */
  3414. }
  3415.  
  3416. /* Clear the cursor of frame F to background color,
  3417.    and mark the cursor as not shown.
  3418.    This is used when the text where the cursor is
  3419.    is about to be rewritten.  */
  3420.  
  3421. static void
  3422. clear_cursor (f)
  3423.      struct frame *f;
  3424. {
  3425.   int mask;
  3426.  
  3427.   if (! FRAME_VISIBLE_P (f)
  3428.       || f->phys_cursor_x < 0)
  3429.     return;
  3430.  
  3431. #ifdef HAVE_X11
  3432.   x_display_cursor (f, 0);
  3433. #else /* ! defined (HAVE_X11) */
  3434.   XPixSet (FRAME_X_WINDOW (f),
  3435.        CHAR_TO_PIXEL_COL (f, f->phys_cursor_x),
  3436.        CHAR_TO_PIXEL_ROW (f, f->phys_cursor_y),
  3437.        FONT_WIDTH (f->display.x->font), FONT_HEIGHT (f->display.x->font),
  3438.        f->display.x->background_pixel);
  3439. #endif /* ! defined (HAVE_X11) */
  3440.   f->phys_cursor_x = -1;
  3441. }
  3442.  
  3443. /* Redraw the glyph at ROW, COLUMN on frame F, in the style
  3444.    HIGHLIGHT.  HIGHLIGHT is as defined for dumpglyphs.  Return the
  3445.    glyph drawn.  */
  3446.  
  3447. static void
  3448. x_draw_single_glyph (f, row, column, glyph, highlight)
  3449.      struct frame *f;
  3450.      int row, column;
  3451.      GLYPH glyph;
  3452.      int highlight;
  3453. {
  3454.   dumpglyphs (f,
  3455.           CHAR_TO_PIXEL_COL (f, column),
  3456.           CHAR_TO_PIXEL_ROW (f, row),
  3457.           &glyph, 1, highlight);
  3458. }
  3459.  
  3460. static void
  3461. x_display_bar_cursor (f, on)
  3462.      struct frame *f;
  3463.      int on;
  3464. {
  3465.   struct frame_glyphs *current_glyphs = FRAME_CURRENT_GLYPHS (f);
  3466.  
  3467.   /* This is pointless on invisible frames, and dangerous on garbaged
  3468.      frames; in the latter case, the frame may be in the midst of
  3469.      changing its size, and curs_x and curs_y may be off the frame.  */
  3470.   if (! FRAME_VISIBLE_P (f) || FRAME_GARBAGED_P (f))
  3471.     return;
  3472.  
  3473.   if (! on && f->phys_cursor_x < 0)
  3474.     return;
  3475.  
  3476.   /* If we're not updating, then we want to use the current frame's
  3477.      cursor position, not our local idea of where the cursor ought to be.  */
  3478.   if (f != updating_frame)
  3479.     {
  3480.       curs_x = FRAME_CURSOR_X (f);
  3481.       curs_y = FRAME_CURSOR_Y (f);
  3482.     }
  3483.  
  3484.   /* If there is anything wrong with the current cursor state, remove it.  */
  3485.   if (f->phys_cursor_x >= 0
  3486.       && (!on
  3487.       || f->phys_cursor_x != curs_x
  3488.       || f->phys_cursor_y != curs_y
  3489.       || f->display.x->current_cursor != bar_cursor))
  3490.     {
  3491.       /* Erase the cursor by redrawing the character underneath it.  */
  3492.       x_draw_single_glyph (f, f->phys_cursor_y, f->phys_cursor_x,
  3493.                f->phys_cursor_glyph,
  3494.                current_glyphs->highlight[f->phys_cursor_y]);
  3495.       f->phys_cursor_x = -1;
  3496.     }
  3497.  
  3498.   /* If we now need a cursor in the new place or in the new form, do it so.  */
  3499.   if (on
  3500.       && (f->phys_cursor_x < 0
  3501.       || (f->display.x->current_cursor != bar_cursor)))
  3502.     {
  3503.       f->phys_cursor_glyph
  3504.     = ((current_glyphs->enable[curs_y]
  3505.         && curs_x < current_glyphs->used[curs_y])
  3506.        ? current_glyphs->glyphs[curs_y][curs_x]
  3507.        : SPACEGLYPH);
  3508.       XFillRectangle (x_current_display, FRAME_X_WINDOW (f),
  3509.               f->display.x->cursor_gc,
  3510.               CHAR_TO_PIXEL_COL (f, curs_x),
  3511.               CHAR_TO_PIXEL_ROW (f, curs_y),
  3512.               1, FONT_HEIGHT (f->display.x->font));
  3513.  
  3514.       f->phys_cursor_x = curs_x;
  3515.       f->phys_cursor_y = curs_y;
  3516.  
  3517.       f->display.x->current_cursor = bar_cursor;
  3518.     }
  3519.  
  3520.   if (updating_frame != f)
  3521.     XFlushQueue ();
  3522. }
  3523.  
  3524.  
  3525. /* Turn the displayed cursor of frame F on or off according to ON.
  3526.    If ON is nonzero, where to put the cursor is specified
  3527.    by F->cursor_x and F->cursor_y.  */
  3528.  
  3529. static void
  3530. x_display_box_cursor (f, on)
  3531.      struct frame *f;
  3532.      int on;
  3533. {
  3534.   struct frame_glyphs *current_glyphs = FRAME_CURRENT_GLYPHS (f);
  3535.  
  3536.   /* This is pointless on invisible frames, and dangerous on garbaged
  3537.      frames; in the latter case, the frame may be in the midst of
  3538.      changing its size, and curs_x and curs_y may be off the frame.  */
  3539.   if (! FRAME_VISIBLE_P (f) || FRAME_GARBAGED_P (f))
  3540.     return;
  3541.  
  3542.   /* If cursor is off and we want it off, return quickly.  */
  3543.   if (!on && f->phys_cursor_x < 0)
  3544.     return;
  3545.  
  3546.   /* If we're not updating, then we want to use the current frame's
  3547.      cursor position, not our local idea of where the cursor ought to be.  */
  3548.   if (f != updating_frame)
  3549.     {
  3550.       curs_x = FRAME_CURSOR_X (f);
  3551.       curs_y = FRAME_CURSOR_Y (f);
  3552.     }
  3553.  
  3554.   /* If cursor is currently being shown and we don't want it to be
  3555.      or it is in the wrong place,
  3556.      or we want a hollow box and it's not so, (pout!)
  3557.      erase it.  */
  3558.   if (f->phys_cursor_x >= 0
  3559.       && (!on
  3560.       || f->phys_cursor_x != curs_x
  3561.       || f->phys_cursor_y != curs_y
  3562.       || (f->display.x->current_cursor != hollow_box_cursor
  3563.           && (f != x_highlight_frame))))
  3564.     {
  3565.       /* Erase the cursor by redrawing the character underneath it.  */
  3566.       x_draw_single_glyph (f, f->phys_cursor_y, f->phys_cursor_x,
  3567.                f->phys_cursor_glyph,
  3568.                current_glyphs->highlight[f->phys_cursor_y]);
  3569.       f->phys_cursor_x = -1;
  3570.     }
  3571.  
  3572.   /* If we want to show a cursor,
  3573.      or we want a box cursor and it's not so,
  3574.      write it in the right place.  */
  3575.   if (on
  3576.       && (f->phys_cursor_x < 0
  3577.       || (f->display.x->current_cursor != filled_box_cursor
  3578.           && f == x_highlight_frame)))
  3579.     {
  3580.       f->phys_cursor_glyph
  3581.     = ((current_glyphs->enable[curs_y]
  3582.         && curs_x < current_glyphs->used[curs_y])
  3583.        ? current_glyphs->glyphs[curs_y][curs_x]
  3584.        : SPACEGLYPH);
  3585.       if (f != x_highlight_frame)
  3586.     {
  3587.       x_draw_box (f);
  3588.       f->display.x->current_cursor = hollow_box_cursor;
  3589.     }
  3590.       else
  3591.     {
  3592.       x_draw_single_glyph (f, curs_y, curs_x,
  3593.                    f->phys_cursor_glyph, 2);
  3594.       f->display.x->current_cursor = filled_box_cursor;
  3595.     }
  3596.  
  3597.       f->phys_cursor_x = curs_x;
  3598.       f->phys_cursor_y = curs_y;
  3599.     }
  3600.  
  3601.   if (updating_frame != f)
  3602.     XFlushQueue ();
  3603. }
  3604.  
  3605. x_display_cursor (f, on)
  3606.      struct frame *f;
  3607.      int on;
  3608. {
  3609.   if (FRAME_DESIRED_CURSOR (f) == filled_box_cursor)
  3610.     x_display_box_cursor (f, on);
  3611.   else if (FRAME_DESIRED_CURSOR (f) == bar_cursor)
  3612.     x_display_bar_cursor (f, on);
  3613.   else
  3614.     /* Those are the only two we have implemented!  */
  3615.     abort ();
  3616. }
  3617.  
  3618. /* Icons.  */
  3619.  
  3620. /* Refresh bitmap kitchen sink icon for frame F
  3621.    when we get an expose event for it. */
  3622.  
  3623. refreshicon (f)
  3624.      struct frame *f;
  3625. {
  3626. #ifdef HAVE_X11
  3627.   /* Normally, the window manager handles this function. */
  3628. #else /* ! defined (HAVE_X11) */
  3629.   int mask;
  3630.  
  3631.   if (f->display.x->icon_bitmap_flag)
  3632.     XBitmapBitsPut (f->display.x->icon_desc, 0,  0, sink_width, sink_height,
  3633.             sink_bits, BlackPixel, WHITE_PIX_DEFAULT, 
  3634.             icon_bitmap, GXcopy, AllPlanes);
  3635.   else
  3636.     {
  3637.       extern struct frame *selected_frame;
  3638.       struct Lisp_String *str;
  3639.       unsigned char *string;
  3640.  
  3641.       string
  3642.     = XSTRING (XBUFFER (XWINDOW (f->selected_window)->buffer)->name)->data;
  3643.  
  3644.       if (f->display.x->icon_label != string)
  3645.     {
  3646.       f->display.x->icon_label = string;
  3647.       XChangeWindow (f->display.x->icon_desc,
  3648.              XQueryWidth (string, icon_font_info->id) + 10,
  3649.              icon_font_info->height + 10);
  3650.     }
  3651.  
  3652.       XText (f->display.x->icon_desc, 5, 5, string,
  3653.          str->size, icon_font_info->id,
  3654.          BLACK_PIX_DEFAULT, WHITE_PIX_DEFAULT);
  3655.     }
  3656.   XFlushQueue ();
  3657. #endif /* ! defined (HAVE_X11) */
  3658. }
  3659.  
  3660. /* Make the x-window of frame F use the gnu icon bitmap.  */
  3661.  
  3662. int
  3663. x_bitmap_icon (f)
  3664.      struct frame *f;
  3665. {
  3666.   int mask;
  3667.   Window icon_window;
  3668.  
  3669.   if (FRAME_X_WINDOW (f) == 0)
  3670.     return 1;
  3671.  
  3672. #ifdef HAVE_X11
  3673.   if (! icon_bitmap)
  3674.     icon_bitmap =
  3675.       XCreateBitmapFromData (x_current_display, FRAME_X_WINDOW (f),
  3676.                  gnu_bits, gnu_width, gnu_height);
  3677.   x_wm_set_icon_pixmap (f, icon_bitmap);
  3678.   f->display.x->icon_bitmap_flag = 1;
  3679. #else /* ! defined (HAVE_X11) */
  3680.   if (f->display.x->icon_desc)
  3681.     {
  3682.       XClearIconWindow (FRAME_X_WINDOW (f));
  3683.       XDestroyWindow (f->display.x->icon_desc);
  3684.     }
  3685.  
  3686.   icon_window = XCreateWindow (f->display.x->parent_desc,
  3687.                    0, 0, sink_width, sink_height,
  3688.                    2, WhitePixmap, (Pixmap) NULL);
  3689.  
  3690.   if (icon_window == 0)
  3691.     return 1;
  3692.  
  3693.   XSetIconWindow (FRAME_X_WINDOW (f), icon_window);
  3694.   XSelectInput (icon_window, ExposeWindow | UnmapWindow);
  3695.  
  3696.   f->display.x->icon_desc = icon_window;
  3697.   f->display.x->icon_bitmap_flag = 1;
  3698.  
  3699.   if (icon_bitmap == 0)
  3700.     icon_bitmap
  3701.       = XStoreBitmap (sink_mask_width, sink_mask_height, sink_mask_bits);
  3702. #endif /* ! defined (HAVE_X11) */
  3703.  
  3704.   return 0;
  3705. }
  3706.  
  3707.  
  3708. /* Make the x-window of frame F use a rectangle with text.  */
  3709.  
  3710. int
  3711. x_text_icon (f, icon_name)
  3712.      struct frame *f;
  3713.      char *icon_name;
  3714. {
  3715. #ifndef HAVE_X11
  3716.   int mask;
  3717.   int width;
  3718.   Window icon_window;
  3719.   char *X_DefaultValue;
  3720.   Bitmap b1;
  3721.  
  3722. #ifndef WhitePixel
  3723. #define WhitePixel 1
  3724. #endif /* WhitePixel */
  3725.  
  3726. #ifndef BlackPixel
  3727. #define BlackPixel 0
  3728. #endif /* BlackPixel */
  3729. #endif /* HAVE_X11 */
  3730.   
  3731.   if (FRAME_X_WINDOW (f) == 0)
  3732.     return 1;
  3733.  
  3734. #ifdef HAVE_X11
  3735.   if (icon_name)
  3736.     f->display.x->icon_label = icon_name;
  3737.   else
  3738.     if (! f->display.x->icon_label)
  3739.       f->display.x->icon_label = " *emacs* ";
  3740.   
  3741. #if 0
  3742.   XSetIconName (x_current_display, FRAME_X_WINDOW (f),
  3743.         (char *) f->display.x->icon_label);
  3744. #endif
  3745.   
  3746.   f->display.x->icon_bitmap_flag = 0;
  3747.   x_wm_set_icon_pixmap (f, 0);
  3748. #else /* ! defined (HAVE_X11) */
  3749.   if (icon_font_info == 0)
  3750.     icon_font_info
  3751.       = XGetFont (XGetDefault (XDISPLAY
  3752.                    (char *) XSTRING (Vinvocation_name)->data,
  3753.                    "BodyFont"));
  3754.  
  3755.   if (f->display.x->icon_desc)
  3756.     {
  3757.       XClearIconWindow (XDISPLAY FRAME_X_WINDOW (f));
  3758.       XDestroyWindow (XDISPLAY f->display.x->icon_desc);
  3759.     }
  3760.  
  3761.   if (icon_name)
  3762.     f->display.x->icon_label = (unsigned char *) icon_name;
  3763.   else
  3764.     if (! f->display.x->icon_label)
  3765.       f->display.x->icon_label = XSTRING (f->name)->data;
  3766.  
  3767.   width = XStringWidth (f->display.x->icon_label, icon_font_info, 0, 0);
  3768.   icon_window = XCreateWindow (f->display.x->parent_desc,
  3769.                    f->display.x->left_pos,
  3770.                    f->display.x->top_pos,
  3771.                    width + 10, icon_font_info->height + 10,
  3772.                    2, BlackPixmap, WhitePixmap);
  3773.  
  3774.   if (icon_window == 0)
  3775.     return 1;
  3776.  
  3777.   XSetIconWindow (FRAME_X_WINDOW (f), icon_window);
  3778.   XSelectInput (icon_window, ExposeWindow | ExposeRegion | UnmapWindow | ButtonPressed);
  3779.  
  3780.   f->display.x->icon_desc = icon_window;
  3781.   f->display.x->icon_bitmap_flag = 0;
  3782.   f->display.x->icon_label = 0;
  3783. #endif /* ! defined (HAVE_X11) */
  3784.  
  3785.   return 0;
  3786. }
  3787.  
  3788. /* Handling X errors.  */
  3789.  
  3790. /* Shut down Emacs in an orderly fashion, because of a SIGPIPE on the
  3791.    X server's connection, or an error reported via the X protocol.  */
  3792.  
  3793. static SIGTYPE
  3794. x_connection_closed ()
  3795. {
  3796.   if (_Xdebug)
  3797.     abort ();
  3798.  
  3799.   shut_down_emacs (0, 1, Qnil);
  3800.  
  3801.   exit (70);
  3802. }
  3803.  
  3804. /* An X error handler which prints an error message and then kills
  3805.    Emacs.  This is what's normally installed as Xlib's handler for
  3806.    protocol errors.  */
  3807. static int
  3808. x_error_quitter (display, error)
  3809.      Display *display;
  3810.      XErrorEvent *error;
  3811. {
  3812.   char buf[256];
  3813.  
  3814.   /* Note that there is no real way portable across R3/R4 to get the 
  3815.      original error handler.  */
  3816.  
  3817.   XGetErrorText (display, error->error_code, buf, sizeof (buf));
  3818.   fprintf (stderr, "X protocol error: %s on protocol request %d\n",
  3819.        buf, error->request_code);
  3820.  
  3821. #if 0
  3822.   /* While we're testing Emacs 19, we'll just dump core whenever we
  3823.      get an X error, so we can figure out why it happened.  */
  3824.   abort ();
  3825. #endif
  3826.  
  3827.   x_connection_closed ();
  3828. }
  3829.  
  3830. /* A handler for X IO errors which prints an error message and then
  3831.    kills Emacs.  This is what is always installed as Xlib's handler
  3832.    for I/O errors.  */
  3833. static int
  3834. x_io_error_quitter (display)
  3835.      Display *display;
  3836. {
  3837.   fprintf (stderr, "Connection to X server %s lost.\n",
  3838.        XDisplayName (DisplayString (display)));
  3839.  
  3840. #if 0
  3841.   /* While we're testing Emacs 19, we'll just dump core whenever we
  3842.      get an X error, so we can figure out why it happened.  */
  3843.   abort ();
  3844. #endif
  3845.  
  3846.   x_connection_closed ();
  3847. }
  3848.  
  3849. /* A buffer for storing X error messages.  */
  3850. static char *x_caught_error_message;
  3851. #define X_CAUGHT_ERROR_MESSAGE_SIZE 200
  3852.  
  3853. /* An X error handler which stores the error message in
  3854.    x_caught_error_message.  This is what's installed when
  3855.    x_catch_errors is in effect.  */
  3856. static int
  3857. x_error_catcher (display, error)
  3858.      Display *display;
  3859.      XErrorEvent *error;
  3860. {
  3861.   XGetErrorText (display, error->error_code,
  3862.          x_caught_error_message, X_CAUGHT_ERROR_MESSAGE_SIZE);
  3863. }
  3864.  
  3865.  
  3866. /* Begin trapping X errors.
  3867.  
  3868.    After calling this function, X protocol errors no longer cause
  3869.    Emacs to exit; instead, they are recorded in x_cfc_error_message.
  3870.  
  3871.    Calling x_check_errors signals an Emacs error if an X error has
  3872.    occurred since the last call to x_catch_errors or x_check_errors.
  3873.  
  3874.    Calling x_uncatch_errors resumes the normal error handling.  */
  3875.  
  3876. void x_catch_errors(), x_check_errors (), x_uncatch_errors ();
  3877.  
  3878. void
  3879. x_catch_errors ()
  3880. {
  3881.   /* Make sure any errors from previous requests have been dealt with.  */
  3882.   XSync (x_current_display, False);
  3883.  
  3884.   /* Set up the error buffer.  */
  3885.   x_caught_error_message
  3886.     = (char*) xmalloc (X_CAUGHT_ERROR_MESSAGE_SIZE);
  3887.   x_caught_error_message[0] = '\0';
  3888.  
  3889.   /* Install our little error handler.  */
  3890.   XHandleError (x_error_catcher);
  3891. }
  3892.  
  3893. /* If any X protocol errors have arrived since the last call to
  3894.    x_catch_errors or x_check_errors, signal an Emacs error using
  3895.    sprintf (a buffer, FORMAT, the x error message text) as the text.  */
  3896. void
  3897. x_check_errors (format)
  3898.      char *format;
  3899. {
  3900.   /* Make sure to catch any errors incurred so far.  */
  3901.   XSync (x_current_display, False);
  3902.  
  3903.   if (x_caught_error_message[0])
  3904.     {
  3905.       char buf[X_CAUGHT_ERROR_MESSAGE_SIZE + 56];
  3906.  
  3907.       sprintf (buf, format, x_caught_error_message);
  3908.       x_uncatch_errors ();
  3909.       error (buf);
  3910.     }
  3911. }
  3912.  
  3913. void
  3914. x_uncatch_errors ()
  3915. {
  3916.   xfree (x_caught_error_message);
  3917.   x_caught_error_message = 0;
  3918.   XHandleError (x_error_quitter);
  3919. }
  3920.  
  3921. #if 0
  3922. static unsigned int x_wire_count;
  3923. x_trace_wire ()
  3924. {
  3925.   fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
  3926. }
  3927. #endif /* ! 0 */
  3928.  
  3929.  
  3930. /* Changing the font of the frame.  */
  3931.  
  3932. /* Set the font of the x-window specified by frame F
  3933.    to the font named NEWNAME.  This is safe to use
  3934.    even before F has an actual x-window.  */
  3935.  
  3936. #ifdef HAVE_X11
  3937.  
  3938. /* A table of all the fonts we have already loaded.  */
  3939. static XFontStruct **x_font_table;
  3940.  
  3941. /* The current capacity of x_font_table.  */
  3942. static int x_font_table_size;
  3943.  
  3944. /* The number of fonts actually stored in x_font_table.
  3945.    x_font_table[n] is used and valid iff 0 <= n < n_fonts.
  3946.    0 <= n_fonts <= x_font_table_size.  */
  3947. static int n_fonts;
  3948.  
  3949. Lisp_Object
  3950. x_new_font (f, fontname)
  3951.      struct frame *f;
  3952.      register char *fontname;
  3953. {
  3954.   int already_loaded;
  3955.   int n_matching_fonts;
  3956.   XFontStruct *font_info;
  3957.   char **font_names;
  3958.  
  3959.   /* Get a list of all the fonts that match this name.  Once we
  3960.      have a list of matching fonts, we compare them against the fonts
  3961.      we already have by comparing font ids.  */
  3962.   font_names = (char **) XListFontsWithInfo (x_current_display, fontname,
  3963.                          1024, &n_matching_fonts,
  3964.                          &font_info);
  3965.   /* Apparently it doesn't set n_matching_fonts to zero when it can't
  3966.      find any matches; font_names == 0 is the only clue.  */
  3967.   if (! font_names)
  3968.     n_matching_fonts = 0;
  3969.  
  3970.   /* Don't just give up if n_matching_fonts is 0.
  3971.      Apparently there's a bug on Suns: XListFontsWithInfo can
  3972.      fail to find a font, but XLoadQueryFont may still find it.  */
  3973.  
  3974.   /* See if we've already loaded a matching font. */
  3975.   already_loaded = -1;
  3976.   if (n_matching_fonts != 0)
  3977.     {
  3978.       int i, j;
  3979.  
  3980.       for (i = 0; i < n_fonts; i++)
  3981.     for (j = 0; j < n_matching_fonts; j++)
  3982.       if (x_font_table[i]->fid == font_info[j].fid)
  3983.         {
  3984.           already_loaded = i;
  3985.           fontname = font_names[j];
  3986.           goto found_font;
  3987.         }
  3988.     }
  3989.  found_font:
  3990.   
  3991.   /* If we have, just return it from the table.  */
  3992.   if (already_loaded > 0)
  3993.     f->display.x->font = x_font_table[already_loaded];
  3994.   
  3995.   /* Otherwise, load the font and add it to the table.  */
  3996.   else
  3997.     {
  3998.       int i;
  3999.       XFontStruct *font;
  4000.  
  4001.       /* Try to find a character-cell font in the list.  */
  4002. #if 0 
  4003.       /* A laudable goal, but this isn't how to do it.  */
  4004.       for (i = 0; i < n_matching_fonts; i++)
  4005.     if (! font_info[i].per_char)
  4006.       break;
  4007. #else
  4008.       i = 0;
  4009. #endif
  4010.  
  4011.       /* See comment above.  */
  4012.       if (n_matching_fonts != 0)
  4013.     fontname = font_names[i];
  4014.  
  4015.       font = (XFontStruct *) XLoadQueryFont (x_current_display, fontname);
  4016.       if (! font)
  4017.     {
  4018.       /* Free the information from XListFontsWithInfo.  */
  4019.       if (n_matching_fonts)
  4020.         XFreeFontInfo (font_names, font_info, n_matching_fonts);
  4021.       return Qnil;
  4022.     }
  4023.  
  4024.       /* Do we need to create the table?  */
  4025.       if (x_font_table_size == 0)
  4026.     {
  4027.       x_font_table_size = 16;
  4028.       x_font_table
  4029.         = (XFontStruct **) xmalloc (x_font_table_size
  4030.                     * sizeof (x_font_table[0]));
  4031.     }
  4032.       /* Do we need to grow the table?  */
  4033.       else if (n_fonts >= x_font_table_size)
  4034.     {
  4035.       x_font_table_size *= 2;
  4036.       x_font_table
  4037.         = (XFontStruct **) xrealloc (x_font_table,
  4038.                      (x_font_table_size
  4039.                       * sizeof (x_font_table[0])));
  4040.     }
  4041.  
  4042.       f->display.x->font = x_font_table[n_fonts++] = font;
  4043.     }
  4044.   
  4045.   /* Now make the frame display the given font.  */
  4046.   if (FRAME_X_WINDOW (f) != 0)
  4047.     {
  4048.       XSetFont (x_current_display, f->display.x->normal_gc,
  4049.         f->display.x->font->fid);
  4050.       XSetFont (x_current_display, f->display.x->reverse_gc,
  4051.         f->display.x->font->fid);
  4052.       XSetFont (x_current_display, f->display.x->cursor_gc,
  4053.         f->display.x->font->fid);
  4054.  
  4055.       x_set_window_size (f, f->width, f->height);
  4056.     }
  4057.  
  4058.   {
  4059.     Lisp_Object lispy_name = build_string (fontname);
  4060.  
  4061.  
  4062.     /* Free the information from XListFontsWithInfo.  The data
  4063.        we actually retain comes from XLoadQueryFont.  */
  4064.     XFreeFontInfo (font_names, font_info, n_matching_fonts);
  4065.  
  4066.     return lispy_name;
  4067.   }
  4068. }
  4069. #else /* ! defined (HAVE_X11) */
  4070. x_new_font (f, newname)
  4071.      struct frame *f;
  4072.      register char *newname;
  4073. {
  4074.   FONT_TYPE *temp;
  4075.   int mask;
  4076.  
  4077.   temp = XGetFont (newname);
  4078.   if (temp == (FONT_TYPE *) 0)
  4079.     return 1;
  4080.  
  4081.   if (f->display.x->font)
  4082.     XLoseFont (f->display.x->font);
  4083.  
  4084.   f->display.x->font = temp;
  4085.  
  4086.   if (FRAME_X_WINDOW (f) != 0)
  4087.     x_set_window_size (f, f->width, f->height);
  4088.  
  4089.   return 0;
  4090. }
  4091. #endif /* ! defined (HAVE_X11) */
  4092.  
  4093. /* X Window sizes and positions.  */
  4094.  
  4095. x_calc_absolute_position (f)
  4096.      struct frame *f;
  4097. {
  4098. #ifdef HAVE_X11
  4099.   if (f->display.x->left_pos < 0)
  4100.     f->display.x->left_pos = (x_screen_width 
  4101.                   - 2 * f->display.x->border_width
  4102.                   - PIXEL_WIDTH (f)
  4103.                   + f->display.x->left_pos);
  4104.  
  4105.   if (f->display.x->top_pos < 0)
  4106.     f->display.x->top_pos = (x_screen_height
  4107.                  - 2 * f->display.x->border_width
  4108.                  - PIXEL_HEIGHT (f)
  4109.                  + f->display.x->top_pos);
  4110. #else /* ! defined (HAVE_X11) */
  4111.   WINDOWINFO_TYPE parentinfo;
  4112.  
  4113.   XGetWindowInfo (FRAME_X_WINDOW (f), &parentinfo);
  4114.  
  4115.   if (f->display.x->left_pos < 0)
  4116.     f->display.x->left_pos = parentinfo.width + (f->display.x->left_pos + 1)
  4117.       - PIXEL_WIDTH (f) - 2 * f->display.x->internal_border_width;
  4118.  
  4119.   if (f->display.x->top_pos < 0)
  4120.     f->display.x->top_pos = parentinfo.height + (f->display.x->top_pos + 1)
  4121.       - PIXEL_HEIGHT (f) - 2 * f->display.x->internal_border_width;
  4122. #endif /* ! defined (HAVE_X11) */
  4123. }
  4124.  
  4125. x_set_offset (f, xoff, yoff)
  4126.      struct frame *f;
  4127.      register int xoff, yoff;
  4128. {
  4129.   f->display.x->top_pos = yoff;
  4130.   f->display.x->left_pos = xoff;
  4131.   x_calc_absolute_position (f);
  4132.  
  4133.   BLOCK_INPUT;
  4134.   XMoveWindow (XDISPLAY FRAME_X_WINDOW (f),
  4135.            f->display.x->left_pos, f->display.x->top_pos);
  4136. #ifdef HAVE_X11
  4137.   x_wm_set_size_hint (f, 0);
  4138. #endif /* ! defined (HAVE_X11) */
  4139.   UNBLOCK_INPUT;
  4140. }
  4141.  
  4142. /* Call this to change the size of frame F's x-window. */
  4143.  
  4144. x_set_window_size (f, cols, rows)
  4145.      struct frame *f;
  4146.      int cols, rows;
  4147. {
  4148.   int pixelwidth, pixelheight;
  4149.   int mask;
  4150.  
  4151.   BLOCK_INPUT;
  4152.  
  4153.   check_frame_size (f, &rows, &cols);
  4154.   f->display.x->vertical_scroll_bar_extra =
  4155.     (FRAME_HAS_VERTICAL_SCROLL_BARS (f)
  4156.      ? VERTICAL_SCROLL_BAR_PIXEL_WIDTH (f)
  4157.      : 0);
  4158.   pixelwidth = CHAR_TO_PIXEL_WIDTH (f, cols);
  4159.   pixelheight = CHAR_TO_PIXEL_HEIGHT (f, rows);
  4160.  
  4161. #ifdef HAVE_X11
  4162.   x_wm_set_size_hint (f, 0);
  4163. #endif /* ! defined (HAVE_X11) */
  4164.   XChangeWindowSize (FRAME_X_WINDOW (f), pixelwidth, pixelheight);
  4165.  
  4166.   /* Now, strictly speaking, we can't be sure that this is accurate,
  4167.      but the window manager will get around to dealing with the size
  4168.      change request eventually, and we'll hear how it went when the
  4169.      ConfigureNotify event gets here.
  4170.  
  4171.      We could just not bother storing any of this information here,
  4172.      and let the ConfigureNotify event set everything up, but that
  4173.      might be kind of confusing to the lisp code, since size changes
  4174.      wouldn't be reported in the frame parameters until some random
  4175.      point in the future when the ConfigureNotify event arrives.  */
  4176.   change_frame_size (f, rows, cols, 0, 0);
  4177.   PIXEL_WIDTH (f) = pixelwidth;
  4178.   PIXEL_HEIGHT (f) = pixelheight;
  4179.  
  4180.   /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
  4181.      receive in the ConfigureNotify event; if we get what we asked
  4182.      for, then the event won't cause the screen to become garbaged, so
  4183.      we have to make sure to do it here.  */
  4184.   SET_FRAME_GARBAGED (f);
  4185.  
  4186.   XFlushQueue ();
  4187.   UNBLOCK_INPUT;
  4188. }
  4189.  
  4190. #ifndef HAVE_X11
  4191. x_set_resize_hint (f)
  4192.      struct frame *f;
  4193. {
  4194.   XSetResizeHint (FRAME_X_WINDOW (f),
  4195.           2 * f->display.x->internal_border_width,
  4196.           2 * f->display.x->internal_border_width,
  4197.           FONT_WIDTH (f->display.x->font),
  4198.           FONT_HEIGHT (f->display.x->font));
  4199. }
  4200. #endif /* HAVE_X11 */
  4201.  
  4202. /* Mouse warping, focus shifting, raising and lowering.  */
  4203.  
  4204. x_set_mouse_position (f, x, y)
  4205.      struct frame *f;
  4206.      int x, y;
  4207. {
  4208.   int pix_x, pix_y;
  4209.  
  4210.   x_raise_frame (f);
  4211.  
  4212.   pix_x = CHAR_TO_PIXEL_COL (f, x) + FONT_WIDTH  (f->display.x->font) / 2;
  4213.   pix_y = CHAR_TO_PIXEL_ROW (f, y) + FONT_HEIGHT (f->display.x->font) / 2;
  4214.  
  4215.   if (pix_x < 0) pix_x = 0;
  4216.   if (pix_x > PIXEL_WIDTH (f)) pix_x = PIXEL_WIDTH (f);
  4217.  
  4218.   if (pix_y < 0) pix_y = 0;
  4219.   if (pix_y > PIXEL_HEIGHT (f)) pix_y = PIXEL_HEIGHT (f);
  4220.  
  4221.   BLOCK_INPUT;
  4222.  
  4223.   XWarpMousePointer (FRAME_X_WINDOW (f), pix_x, pix_y);
  4224.   UNBLOCK_INPUT;
  4225. }
  4226.  
  4227. #ifdef HAVE_X11
  4228. x_focus_on_frame (f)
  4229.      struct frame *f;
  4230. {
  4231.   x_raise_frame (f);
  4232. #if 0
  4233.   /* I don't think that the ICCCM allows programs to do things like this
  4234.      without the interaction of the window manager.  Whatever you end up
  4235.      doing with this code, do it to x_unfocus_frame too.  */
  4236.   XSetInputFocus (x_current_display, FRAME_X_WINDOW (f),
  4237.           RevertToPointerRoot, CurrentTime);
  4238. #endif /* ! 0 */
  4239. }
  4240.  
  4241. x_unfocus_frame (f)
  4242.      struct frame *f;
  4243. {
  4244. #if 0
  4245.   /* Look at the remarks in x_focus_on_frame.  */
  4246.   if (x_focus_frame == f)
  4247.     XSetInputFocus (x_current_display, PointerRoot,
  4248.             RevertToPointerRoot, CurrentTime);
  4249. #endif /* ! 0 */
  4250. }
  4251.  
  4252. #endif /* ! defined (HAVE_X11) */
  4253.  
  4254. /* Raise frame F.  */
  4255.  
  4256. x_raise_frame (f)
  4257.      struct frame *f;
  4258. {
  4259.   if (f->async_visible)
  4260.     {
  4261.       BLOCK_INPUT;
  4262.       XRaiseWindow (XDISPLAY FRAME_X_WINDOW (f));
  4263.       XFlushQueue ();
  4264.       UNBLOCK_INPUT;
  4265.     }
  4266. }
  4267.  
  4268. /* Lower frame F.  */
  4269.  
  4270. x_lower_frame (f)
  4271.      struct frame *f;
  4272. {
  4273.   if (f->async_visible)
  4274.     {
  4275.       BLOCK_INPUT;
  4276.       XLowerWindow (XDISPLAY FRAME_X_WINDOW (f));
  4277.       XFlushQueue ();
  4278.       UNBLOCK_INPUT;
  4279.     }
  4280. }
  4281.  
  4282. static void
  4283. XTframe_raise_lower (f, raise)
  4284.      FRAME_PTR f;
  4285.      int raise;
  4286. {
  4287.   if (raise)
  4288.     x_raise_frame (f);
  4289.   else
  4290.     x_lower_frame (f);
  4291. }
  4292.  
  4293.  
  4294. /* Change from withdrawn state to mapped state. */
  4295.  
  4296. x_make_frame_visible (f)
  4297.      struct frame *f;
  4298. {
  4299.   int mask;
  4300.  
  4301.   BLOCK_INPUT;
  4302.  
  4303.   if (! FRAME_VISIBLE_P (f))
  4304.     {
  4305. #ifdef HAVE_X11
  4306.       if (! EQ (Vx_no_window_manager, Qt))
  4307.     x_wm_set_window_state (f, NormalState);
  4308.  
  4309.       XMapWindow (XDISPLAY FRAME_X_WINDOW (f));
  4310.       if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
  4311.     XMapSubwindows (x_current_display, FRAME_X_WINDOW (f));
  4312. #else /* ! defined (HAVE_X11) */
  4313.       XMapWindow (XDISPLAY FRAME_X_WINDOW (f));
  4314.       if (f->display.x->icon_desc != 0)
  4315.     XUnmapWindow (f->display.x->icon_desc);
  4316.  
  4317.       /* Handled by the MapNotify event for X11 */
  4318.       f->async_visible = 1;
  4319.       f->async_iconified = 0;
  4320.  
  4321.       /* NOTE: this may cause problems for the first frame. */
  4322.       XTcursor_to (0, 0);
  4323. #endif /* ! defined (HAVE_X11) */
  4324.     }
  4325.  
  4326.   XFlushQueue ();
  4327.  
  4328.   UNBLOCK_INPUT;
  4329. }
  4330.  
  4331. /* Change from mapped state to withdrawn state. */
  4332.  
  4333. x_make_frame_invisible (f)
  4334.      struct frame *f;
  4335. {
  4336.   int mask;
  4337.  
  4338.   /* Don't keep the highlight on an invisible frame.  */
  4339.   if (x_highlight_frame == f)
  4340.     x_highlight_frame = 0;
  4341.  
  4342.   if (! f->async_visible && ! f->async_iconified)
  4343.     return;
  4344.  
  4345.   BLOCK_INPUT;
  4346.  
  4347. #ifdef HAVE_X11R4
  4348.  
  4349.   if (! XWithdrawWindow (x_current_display, FRAME_X_WINDOW (f),
  4350.              DefaultScreen (x_current_display)))
  4351.     {
  4352.       UNBLOCK_INPUT_RESIGNAL;
  4353.       error ("can't notify window manager of window withdrawal");
  4354.     }
  4355.  
  4356. #else /* ! defined (HAVE_X11R4) */
  4357. #ifdef HAVE_X11
  4358.  
  4359.   /*  Tell the window manager what we're going to do.  */
  4360.   if (! EQ (Vx_no_window_manager, Qt))
  4361.     {
  4362.       XEvent unmap;
  4363.  
  4364.       unmap.xunmap.type = UnmapNotify;
  4365.       unmap.xunmap.window = FRAME_X_WINDOW (f);
  4366.       unmap.xunmap.event = DefaultRootWindow (x_current_display);
  4367.       unmap.xunmap.from_configure = False;
  4368.       if (! XSendEvent (x_current_display,
  4369.             DefaultRootWindow (x_current_display),
  4370.             False,
  4371.             SubstructureRedirectMask|SubstructureNotifyMask,
  4372.             &unmap))
  4373.     {
  4374.       UNBLOCK_INPUT_RESIGNAL;
  4375.       error ("can't notify window manager of withdrawal");
  4376.     }
  4377.     }
  4378.  
  4379.   /* Unmap the window ourselves.  Cheeky!  */
  4380.   XUnmapWindow (x_current_display, FRAME_X_WINDOW (f));
  4381.  
  4382. #else /* ! defined (HAVE_X11) */
  4383.  
  4384.   XUnmapWindow (FRAME_X_WINDOW (f));
  4385.   f->async_visible = 0;        /* Handled by the UnMap event for X11 */
  4386.   if (f->display.x->icon_desc != 0)
  4387.     XUnmapWindow (f->display.x->icon_desc);
  4388.  
  4389. #endif /* ! defined (HAVE_X11) */
  4390. #endif /* ! defined (HAVE_X11R4) */
  4391.  
  4392.   XFlushQueue ();
  4393.   UNBLOCK_INPUT;
  4394. }
  4395.  
  4396. /* Change window state from mapped to iconified. */
  4397.  
  4398. x_iconify_frame (f)
  4399.      struct frame *f;
  4400. {
  4401.   int mask;
  4402.  
  4403.   /* Don't keep the highlight on an invisible frame.  */
  4404.   if (x_highlight_frame == f)
  4405.     x_highlight_frame = 0;
  4406.  
  4407.   if (f->async_iconified)
  4408.     return;
  4409.  
  4410.   BLOCK_INPUT;
  4411.  
  4412. #ifdef HAVE_X11
  4413.   /* Since we don't know which revision of X we're running, we'll use both
  4414.      the X11R3 and X11R4 techniques.  I don't know if this is a good idea.  */
  4415.  
  4416.   /* X11R4: send a ClientMessage to the window manager using the
  4417.      WM_CHANGE_STATE type.  */
  4418.   {
  4419.     XEvent message;
  4420.     
  4421.     message.xclient.window = FRAME_X_WINDOW (f);
  4422.     message.xclient.type = ClientMessage;
  4423.     message.xclient.message_type = Xatom_wm_change_state;
  4424.     message.xclient.format = 32;
  4425.     message.xclient.data.l[0] = IconicState;
  4426.  
  4427.     if (! XSendEvent (x_current_display,
  4428.               DefaultRootWindow (x_current_display),
  4429.               False,
  4430.               SubstructureRedirectMask | SubstructureNotifyMask,
  4431.               &message))
  4432.       {
  4433.     UNBLOCK_INPUT_RESIGNAL;
  4434.     error ("Can't notify window manager of iconification.");
  4435.       }
  4436.   }
  4437.  
  4438.   /* X11R3: set the initial_state field of the window manager hints to 
  4439.      IconicState.  */
  4440.   x_wm_set_window_state (f, IconicState);
  4441.  
  4442.   f->async_iconified = 1;
  4443. #else /* ! defined (HAVE_X11) */
  4444.   XUnmapWindow (XDISPLAY FRAME_X_WINDOW (f));
  4445.  
  4446.   f->async_visible = 0;        /* Handled in the UnMap event for X11. */
  4447.   if (f->display.x->icon_desc != 0)
  4448.     {
  4449.       XMapWindow (XDISPLAY f->display.x->icon_desc);
  4450.       refreshicon (f);
  4451.     }
  4452. #endif /* ! defined (HAVE_X11) */
  4453.  
  4454.   XFlushQueue ();
  4455.   UNBLOCK_INPUT;
  4456. }
  4457.  
  4458. /* Destroy the X window of frame F.  */
  4459.  
  4460. x_destroy_window (f)
  4461.      struct frame *f;
  4462. {
  4463.   BLOCK_INPUT;
  4464.  
  4465.   if (f->display.x->icon_desc != 0)
  4466.     XDestroyWindow (XDISPLAY f->display.x->icon_desc);
  4467.   XDestroyWindow (XDISPLAY f->display.x->window_desc);
  4468.   free_frame_faces (f);
  4469.   XFlushQueue ();
  4470.  
  4471.   xfree (f->display.x);
  4472.   f->display.x = 0;
  4473.   if (f == x_focus_frame)
  4474.     x_focus_frame = 0;
  4475.   if (f == x_highlight_frame)
  4476.     x_highlight_frame = 0;
  4477.  
  4478.   UNBLOCK_INPUT;
  4479. }
  4480.  
  4481. /* Manage event queues for X10.  */
  4482.  
  4483. #ifndef HAVE_X11
  4484.  
  4485. /* Manage event queues.
  4486.  
  4487.    This code is only used by the X10 support.
  4488.  
  4489.    We cannot leave events in the X queue and get them when we are ready
  4490.    because X does not provide a subroutine to get only a certain kind
  4491.    of event but not block if there are no queued events of that kind.
  4492.  
  4493.    Therefore, we must examine events as they come in and copy events
  4494.    of certain kinds into our private queues.
  4495.  
  4496.    All ExposeRegion events are put in x_expose_queue.
  4497.    All ButtonPressed and ButtonReleased events are put in x_mouse_queue.  */
  4498.  
  4499.  
  4500. /* Write the event *P_XREP into the event queue *QUEUE.
  4501.    If the queue is full, do nothing, but return nonzero.  */
  4502.  
  4503. int
  4504. enqueue_event (p_xrep, queue)
  4505.      register XEvent *p_xrep;
  4506.      register struct event_queue *queue;
  4507. {
  4508.   int newindex = queue->windex + 1;
  4509.   if (newindex == EVENT_BUFFER_SIZE)
  4510.     newindex = 0;
  4511.   if (newindex == queue->rindex)
  4512.     return -1;
  4513.   queue->xrep[queue->windex] = *p_xrep;
  4514.   queue->windex = newindex;
  4515.   return 0;
  4516. }
  4517.  
  4518. /* Fetch the next event from queue *QUEUE and store it in *P_XREP.
  4519.    If *QUEUE is empty, do nothing and return 0.  */
  4520.  
  4521. int
  4522. dequeue_event (p_xrep, queue)
  4523.      register XEvent *p_xrep;
  4524.      register struct event_queue *queue;
  4525. {
  4526.   if (queue->windex == queue->rindex)
  4527.     return 0;
  4528.   *p_xrep = queue->xrep[queue->rindex++];
  4529.   if (queue->rindex == EVENT_BUFFER_SIZE)
  4530.     queue->rindex = 0;
  4531.   return 1;
  4532. }
  4533.  
  4534. /* Return the number of events buffered in *QUEUE.  */
  4535.  
  4536. int
  4537. queue_event_count (queue)
  4538.      register struct event_queue *queue;
  4539. {
  4540.   int tem = queue->windex - queue->rindex;
  4541.   if (tem >= 0)
  4542.     return tem;
  4543.   return EVENT_BUFFER_SIZE + tem;
  4544. }
  4545.  
  4546. /* Return nonzero if mouse input is pending.  */
  4547.  
  4548. int
  4549. mouse_event_pending_p ()
  4550. {
  4551.   return queue_event_count (&x_mouse_queue);
  4552. }
  4553. #endif /* HAVE_X11 */
  4554.  
  4555. /* Setting window manager hints.  */
  4556.  
  4557. #ifdef HAVE_X11
  4558.  
  4559. x_wm_set_size_hint (f, prompting)
  4560.      struct frame *f;
  4561.      long prompting;
  4562. {
  4563.   XSizeHints size_hints;
  4564.   Window window = FRAME_X_WINDOW (f);
  4565.  
  4566.   size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
  4567.  
  4568.   flexlines = f->height;
  4569.  
  4570.   size_hints.x = f->display.x->left_pos;
  4571.   size_hints.y = f->display.x->top_pos;
  4572.   size_hints.height = PIXEL_HEIGHT (f);
  4573.   size_hints.width = PIXEL_WIDTH (f);
  4574.   size_hints.width_inc = FONT_WIDTH (f->display.x->font);
  4575.   size_hints.height_inc = FONT_HEIGHT (f->display.x->font);
  4576. #if 0
  4577.   size_hints.max_width = x_screen_width - CHAR_TO_PIXEL_WIDTH (f, 0);
  4578.   size_hints.max_height = x_screen_height - CHAR_TO_PIXEL_HEIGHT (f, 0);
  4579. #endif    
  4580.   {
  4581.     int base_width, base_height;
  4582.  
  4583.     base_width = CHAR_TO_PIXEL_WIDTH (f, 0);
  4584.     base_height = CHAR_TO_PIXEL_HEIGHT (f, 0);
  4585.  
  4586.     {
  4587.       int min_rows = 0, min_cols = 0;
  4588.       check_frame_size (f, &min_rows, &min_cols);
  4589.  
  4590.       /* The window manager uses the base width hints to calculate the
  4591.      current number of rows and columns in the frame while
  4592.      resizing; min_width and min_height aren't useful for this
  4593.      purpose, since they might not give the dimensions for a
  4594.      zero-row, zero-column frame.
  4595.  
  4596.      We use the base_width and base_height members if we have
  4597.      them; otherwise, we set the min_width and min_height members
  4598.      to the size for a zero x zero frame.  */
  4599.  
  4600. #ifdef HAVE_X11R4
  4601.       size_hints.flags |= PBaseSize;
  4602.       size_hints.base_width = base_width;
  4603.       size_hints.base_height = base_height;
  4604.       size_hints.min_width  = base_width + min_cols * size_hints.width_inc;
  4605.       size_hints.min_height = base_height + min_rows * size_hints.height_inc;
  4606. #else
  4607.       size_hints.min_width = base_width;
  4608.       size_hints.min_height = base_height;
  4609. #endif
  4610.     }
  4611.  
  4612.   }
  4613.  
  4614.   if (prompting)
  4615.     size_hints.flags |= prompting;
  4616.   else
  4617.     {
  4618.       XSizeHints hints;        /* Sometimes I hate X Windows... */
  4619.       
  4620.       if (XGetNormalHints (x_current_display, window, &hints) == 0)
  4621.     hints.flags = 0;
  4622.       if (hints.flags & PSize)
  4623.     size_hints.flags |= PSize;
  4624.       if (hints.flags & PPosition)
  4625.     size_hints.flags |= PPosition;
  4626.       if (hints.flags & USPosition)
  4627.     size_hints.flags |= USPosition;
  4628.       if (hints.flags & USSize)
  4629.     size_hints.flags |= USSize;
  4630.     }
  4631.  
  4632. #ifdef HAVE_X11R4
  4633.   XSetWMNormalHints (x_current_display, window, &size_hints);
  4634. #else
  4635.   XSetNormalHints (x_current_display, window, &size_hints);
  4636. #endif
  4637. }
  4638.  
  4639. /* Used for IconicState or NormalState */
  4640. x_wm_set_window_state (f, state)
  4641.      struct frame *f;
  4642.      int state;
  4643. {
  4644.   Window window = FRAME_X_WINDOW (f);
  4645.  
  4646.   f->display.x->wm_hints.flags |= StateHint;
  4647.   f->display.x->wm_hints.initial_state = state;
  4648.  
  4649.   XSetWMHints (x_current_display, window, &f->display.x->wm_hints);
  4650. }
  4651.  
  4652. x_wm_set_icon_pixmap (f, icon_pixmap)
  4653.      struct frame *f;
  4654.      Pixmap icon_pixmap;
  4655. {
  4656.   Window window = FRAME_X_WINDOW (f);
  4657.  
  4658.   if (icon_pixmap)
  4659.     {
  4660.       f->display.x->wm_hints.icon_pixmap = icon_pixmap;
  4661.       f->display.x->wm_hints.flags |= IconPixmapHint;
  4662.     }
  4663.   else
  4664.     f->display.x->wm_hints.flags &= ~IconPixmapHint;
  4665.  
  4666.   XSetWMHints (x_current_display, window, &f->display.x->wm_hints);
  4667. }
  4668.  
  4669. x_wm_set_icon_position (f, icon_x, icon_y)
  4670.      struct frame *f;
  4671.      int icon_x, icon_y;
  4672. {
  4673.   Window window = FRAME_X_WINDOW (f);
  4674.  
  4675.   f->display.x->wm_hints.flags |= IconPositionHint;
  4676.   f->display.x->wm_hints.icon_x = icon_x;
  4677.   f->display.x->wm_hints.icon_y = icon_y;
  4678.  
  4679.   XSetWMHints (x_current_display, window, &f->display.x->wm_hints);
  4680. }
  4681.  
  4682.  
  4683. /* Initialization.  */
  4684.  
  4685. void
  4686. x_term_init (display_name)
  4687.      char *display_name;
  4688. {
  4689.   Lisp_Object frame;
  4690.   char *defaultvalue;
  4691. #ifndef F_SETOWN_BUG
  4692. #ifdef F_SETOWN
  4693.   extern int old_fcntl_owner;
  4694. #endif /* ! defined (F_SETOWN) */
  4695. #endif /* F_SETOWN_BUG */
  4696.   
  4697.   x_focus_frame = x_highlight_frame = 0;
  4698.  
  4699.   x_current_display = XOpenDisplay (display_name);
  4700.   if (x_current_display == 0)
  4701.     fatal ("X server %s not responding.\n\
  4702. Check the DISPLAY environment variable or use \"-d\"\n",
  4703.        display_name);
  4704.  
  4705. #ifdef HAVE_X11
  4706.   {
  4707.     int hostname_size = 256;
  4708.  
  4709.     hostname = (char *) xmalloc (hostname_size);
  4710.  
  4711. #if 0
  4712.     XSetAfterFunction (x_current_display, x_trace_wire);
  4713. #endif /* ! 0 */
  4714.  
  4715.     /* Try to get the host name; if the buffer is too short, try
  4716.        again.  Apparently, the only indication gethostname gives of
  4717.        whether the buffer was large enough is the presence or absence
  4718.        of a '\0' in the string.  Eech.  */
  4719.     for (;;)
  4720.       {
  4721.     gethostname (hostname, hostname_size - 1);
  4722.     hostname[hostname_size - 1] = '\0';
  4723.  
  4724.     /* Was the buffer large enough for gethostname to store the '\0'?  */
  4725.     if (strlen (hostname) < hostname_size - 1)
  4726.       break;
  4727.  
  4728.     hostname_size <<= 1;
  4729.     hostname = (char *) xrealloc (hostname, hostname_size);
  4730.       }
  4731.     x_id_name = (char *) xmalloc (XSTRING (Vinvocation_name)->size
  4732.                 + strlen (hostname)
  4733.                 + 2);
  4734.     sprintf (x_id_name, "%s@%s", XSTRING (Vinvocation_name)->data, hostname);
  4735.   }
  4736.  
  4737.   /* Figure out which modifier bits mean what.  */
  4738.   x_find_modifier_meanings ();
  4739.  
  4740.   /* Get the scroll bar cursor.  */
  4741.   x_vertical_scroll_bar_cursor
  4742.     = XCreateFontCursor (x_current_display, XC_sb_v_double_arrow);
  4743.  
  4744. #if 0
  4745.   /* Watch for PropertyNotify events on the root window; we use them
  4746.      to figure out when to invalidate our cache of the cut buffers.  */
  4747.   x_watch_cut_buffer_cache ();
  4748. #endif
  4749.  
  4750.   if (ConnectionNumber (x_current_display) != 0)
  4751.     {
  4752.       dup2 (ConnectionNumber (x_current_display), 0);
  4753.  
  4754. #ifndef SYSV_STREAMS
  4755.       /* Streams somehow keeps track of which descriptor number
  4756.      is being used to talk to X.  So it is not safe to substitute
  4757.      descriptor 0.  But it is safe to make descriptor 0 a copy of it.  */
  4758.       close (ConnectionNumber (x_current_display));
  4759.       ConnectionNumber (x_current_display) = 0;    /* Looks a little strange?
  4760.                          * check the def of the macro;
  4761.                          * it is a genuine lvalue */
  4762. #endif /* SYSV_STREAMS */
  4763.     }
  4764.  
  4765. #endif /* ! defined (HAVE_X11) */
  4766.   
  4767. #ifndef F_SETOWN_BUG
  4768. #ifdef F_SETOWN
  4769.   old_fcntl_owner = fcntl (0, F_GETOWN, 0);
  4770. #ifdef F_SETOWN_SOCK_NEG
  4771.   fcntl (0, F_SETOWN, -getpid ());    /* stdin is a socket here */
  4772. #else /* ! defined (F_SETOWN_SOCK_NEG) */
  4773.   fcntl (0, F_SETOWN, getpid ());
  4774. #endif /* ! defined (F_SETOWN_SOCK_NEG) */
  4775. #endif /* ! defined (F_SETOWN) */
  4776. #endif /* F_SETOWN_BUG */
  4777.  
  4778. #ifdef SIGIO
  4779.   init_sigio ();
  4780. #endif /* ! defined (SIGIO) */
  4781.  
  4782.   /* Must use interrupt input because we cannot otherwise
  4783.      arrange for C-g to be noticed immediately.
  4784.      We cannot connect it to SIGINT.  */
  4785.   Fset_input_mode (Qt, Qnil, Qt, Qnil);
  4786.  
  4787.   expose_all_windows = 0;
  4788.  
  4789.   clear_frame_hook = XTclear_frame;
  4790.   clear_end_of_line_hook = XTclear_end_of_line;
  4791.   ins_del_lines_hook = XTins_del_lines;
  4792.   change_line_highlight_hook = XTchange_line_highlight;
  4793.   insert_glyphs_hook = XTinsert_glyphs;
  4794.   write_glyphs_hook = XTwrite_glyphs;
  4795.   delete_glyphs_hook = XTdelete_glyphs;
  4796.   ring_bell_hook = XTring_bell;
  4797.   reset_terminal_modes_hook = XTreset_terminal_modes;
  4798.   set_terminal_modes_hook = XTset_terminal_modes;
  4799.   update_begin_hook = XTupdate_begin;
  4800.   update_end_hook = XTupdate_end;
  4801.   set_terminal_window_hook = XTset_terminal_window;
  4802.   read_socket_hook = XTread_socket;
  4803.   cursor_to_hook = XTcursor_to;
  4804.   reassert_line_highlight_hook = XTreassert_line_highlight;
  4805.   mouse_position_hook = XTmouse_position;
  4806.   frame_rehighlight_hook = XTframe_rehighlight;
  4807.   frame_raise_lower_hook = XTframe_raise_lower;
  4808.   set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
  4809.   condemn_scroll_bars_hook = XTcondemn_scroll_bars;
  4810.   redeem_scroll_bar_hook = XTredeem_scroll_bar;
  4811.   judge_scroll_bars_hook = XTjudge_scroll_bars;
  4812.   
  4813.   scroll_region_ok = 1;        /* we'll scroll partial frames */
  4814.   char_ins_del_ok = 0;        /* just as fast to write the line */
  4815.   line_ins_del_ok = 1;        /* we'll just blt 'em */
  4816.   fast_clear_end_of_line = 1;    /* X does this well */
  4817.   memory_below_frame = 0;    /* we don't remember what scrolls 
  4818.                    off the bottom */
  4819.   baud_rate = 19200;
  4820.  
  4821.   /* Note that there is no real way portable across R3/R4 to get the 
  4822.      original error handler.  */
  4823.   XHandleError (x_error_quitter);
  4824.   XHandleIOError (x_io_error_quitter);
  4825.  
  4826.   /* Disable Window Change signals;  they are handled by X events. */
  4827. #ifdef SIGWINCH
  4828.   signal (SIGWINCH, SIG_DFL);
  4829. #endif /* ! defined (SIGWINCH) */
  4830.  
  4831.   signal (SIGPIPE, x_connection_closed);
  4832. }
  4833.  
  4834. void
  4835. syms_of_xterm ()
  4836. {
  4837.   staticpro (&last_mouse_scroll_bar);
  4838. }
  4839. #endif /* ! defined (HAVE_X11) */
  4840. #endif /* ! defined (HAVE_X_WINDOWS) */
  4841.